当前位置: 动力学知识库 > 问答 > 编程问答 >

Using jQuery functions on javascript generated DOM elements

问题描述:

This question already has an answer here:

  • Event binding on dynamically created elements?

    16 answers

网友答案:

This is happening because you're attaching your click event listeners directly to elements that don't exist. That is, on the document ready event, you're looking for all elements that match .qtyplus and .qtyminus, but none do. That gives you an empty array of jQuery objects. Then the click handler is attached to every element in that array, but it's empty, so no click handlers are attached.

To get this to work, rather than using the .click() shorthand, you would want to use .on(), e.g.:

$( 'table' ).on( 'click', '.qtyplus', function ( e ) { /* ... */ });

This works because browser click events "bubble" up from a target to its parent elements. jQuery takes advantage of this with .on() by attaching an event listener to a parent element and checking the target of events that bubble up to that element. In this case, it will listen for click events in table, check that the target matches the selector specified (e.g., .qtyplus or .qtyminus), and call the callback if it does.

分享给朋友:
您可能感兴趣的文章:
随机阅读: