There are two ways to solve the problem of a dynamic new element node in jquery that cannot trigger an event , as follows:
To achieve a better presentation, assume that there is code for the following structure under the body of a page:
?
1234567891011 |
<p id=
"pLabel"
>新加一条</p>
<ul id=
"ulLabel"
>
<li class=
"liLabel"
>aaa1</li>
<li class=
"liLabel"
>aaa2</li>
<li class=
"liLabel"
>aaa3</li>
</ul>
<script type=
"text/javascript"
>
$(
"#pLabel"
).click(
function
(){
$(
"#ulLabel"
).append(
‘<li class="liLabel">aaaQ</li>‘
);
//动态像ul的末尾追加一个新元素
});
</script>
|
Method One: Use Live
The live () function binds the selected element to the previous or multiple event handlers, and specifies the function to run when these events occur. The live () function works with the current and future elements of the matching selector. For example, elements created dynamically through a script.
The implementation is as follows:
?
123 |
$( ‘.liLabel‘ ).live( ‘click‘ , function (){ alert( ‘OK‘ ); }); |
Method Two: Use on
You can bind an event by using the on method, which can be bound to its parent or body, as follows:
?
1234567 |
$(
"#ulLabel"
).on(
‘click‘
,
‘.liLabel‘
,
function
(){
alert(
‘OK‘
)
});
或者:
$(
"body"
).on(
‘click‘
,
‘.liLabel‘
,
function
(){
alert(
‘OK‘
)
});
|
Now we can try to try, whether the problem has been solved, I hope this article can really help everyone.
There are two ways to solve the problem of not triggering events for dynamically added element nodes in jquery