最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery onClick Image Event - Stack Overflow

programmeradmin0浏览0评论

I'm trying to make it so when you click on an image, it will do a function inside the document.

Now I am having a bit of trouble and I'm sure this is some stupid mistake but whats wrong here?

<script type="text/javascript">
$.getJSON(";type=suggest&callback=?", function (data) {
    $i = 0;
    $.each(data.streams, function (index, item) {
        $("<img>").attr("src", item.preview.medium).attr("onclick", "").appendTo("#images");
        $i++;
    });
});
</script>

They display correctly, its just that the onclick event doesn't work.

I'm trying to make it so when you click on an image, it will do a function inside the document.

Now I am having a bit of trouble and I'm sure this is some stupid mistake but whats wrong here?

<script type="text/javascript">
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=star&type=suggest&callback=?", function (data) {
    $i = 0;
    $.each(data.streams, function (index, item) {
        $("<img>").attr("src", item.preview.medium).attr("onclick", "").appendTo("#images");
        $i++;
    });
});
</script>

They display correctly, its just that the onclick event doesn't work.

Share Improve this question asked Nov 28, 2013 at 23:03 user3023566user3023566 1691 gold badge1 silver badge12 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 5

Give each of your image a class, like 'leImage'.

Create an event listener like this:

$(".leImage").on("click", function()
{
    // Do stuff, get id of image perhaps?
    var id = this.id;
    // or
    var id = $(this).attr("id");
});

If this is not what you're asking for then you'll have to be more clear :)

First of all set id for image.

<img src="../images/warning.png" id="imageId"/>

After that use this code:

<script>
    $('#imageId').click(function () {
        alert('It works!');
    });
</script>

You are creating elements with jquery.. so just use its methods

$("<img>")
    .attr("src", item.preview.medium)
    .click(function(){ showStream(index);})
    .appendTo("#images");

Or you use this syntax instead

$("<img>", {
    src: item.preview.medium,
    click: function(){showStream(index);}
}).appendTo("#images");

Try this way;

<script type="text/javascript">
$.getJSON("https://api.twitch.tv/kraken/search/streams?q=star&type=suggest&callback=?", function (data) {

    $.each(data.streams, function (index, item) {
        $("<img>").attr("src", item.preview.medium).appendTo("#images");

    });
});


 $("#images img").on("click",function(e){
   alert("your function all")

  })
</script>

The function name after on click is blank?

$("#something").attr("onClick","new_function()");

发布评论

评论列表(0)

  1. 暂无评论