Brief Analysis of Click Event Instance Code for Dynamic Element Binding by jQuery on of Method

  • 2021-06-28 10:52:21
  • OfStack

Previously, 1 has been plagued by this problem. After jQuery version 1.7, on method was added. It was known before that it has superiority over live (), bind (), delegate () and other methods. In the previous project, I wanted to use this to test and found that the dynamically generated tag clicked unresponsively, but the live method can support it, so I can look up data everywhere and ask my netizens.It took a long time to find the answer in one article.

When jQuery uses on to bind dynamically generated elements, it cannot operate directly on this object, but instead selects its non-dynamically generated parent node and finds itself.Let's see the source code.Generated button cardinality item on method clicks invalid live method is valid.

For example, there are two elements below the page:


<input type="button" name="addbtn" value=" Button Add " />
<div id="test">
</div>

Use the jQuery code below to compare and see the difference:


$(function () {
var a = 1,
$_div = $('#test');
$('input[name=addbtn]').on('click', function () {
$_div.append('<input type="button" name="test' + a + '" value=" Button ' + a + '"/>');
a++;
});
// Even Click Events 
$_div.on('click', 'input[name^=test]:even', function () { 
alert(' I am valid on Method , Can you see me: ' + this.value);
});
// Odd Item Binding Click Event   Found clicks invalid, instead use live Method can support 
$('input[name^=test]:odd').on('click', function () { 
alert(' I am invalid on Method , You can't see me ');
});
// Odd Item Binding Click Event   Found clicks invalid, instead use live Method can support 
$('input[name^=test]:odd').live('click', function () {
alert(' I am live Method , Can you see me: ' + this.value);
});
});

Related articles: