简体   繁体   中英

jQuery click function is not attaching click event to anchor

HTML

Inside <div id='foo-bar-baz'> I have a series of image links with unique ids as below

<a href=''><img id='12341234' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>
<a href=''><img id='56785678' class='foo-bar-thumbnail-image' src='/path/to/image.jpg'></a>

Javascript / JQuery

The above div is created by a $.get() to a webservice which returns a chunk of HTML in variable response . On success, the $.get() calls the below function:

var thumbnailsDiv = function (response) 
    {
        var json = $.parseJSON(response);
        $('#foo-bar-baz').html(json.html);
        alert("Setting click functions on thumbnails");
        $('.foo-bar-thumbnail-image').unbind().click(function () {
            alert("I am thumbnail " + $(this).id);
        }, false);
    };

As you can see above, I'm trying to bind a click function to each of the image links. However this is not working (with or without the unbind() ).

After the above code has run, if I inspect the image links in the Dev Tools, I can see that there are two click event attached already to the thumbnails. Neither of these is my function above. The paths for both of them are from other applications libraries embedded on the page: one is labelled 'jQuery' and the other is labelled 'Bubbling' and 'DOM2'. I'm guessing that it is these attached events that mean I can't add my event above, but I don't know enough about jQuery or javascript to know if this is true (I am a server-side developer normally, I don't know front-end stuff at all.)

Any suggestions as to how I get an on-click event working for these elements would be much appreciated, so that I can replace the demo code above with the code I need to run.

You just need to bind the click event to the parent element which already exists on the page.

$('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){
  // what you want to happen when click 
  // occurs on elements that match '.foo-bar-thumbnail-image'
  // within '#foo-bar-baz'
  alert("I am thumbnail " + $(this).id);
});

您应该使用$(document).on('click','.foo-bar-thumbnail-image',function() ...而不是$.click(function()...因为事件处理程序已打开通过JS在页面上呈现的元素。这是一个“委托”事件处理程序 - 你可以在这里阅读更多关于它的信息https://learn.jquery.com/events/event-delegation/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM