简体   繁体   中英

Don't work my jQuery code after append

Don't work my jQuery code after append. how can just change js code and worked it?

I don't use from ides "#aaa or #sss", How do without use them?

DEMO: http://jsfiddle.net/sq4kx/

html:

<a href="" class="qqq">Click Me</a>
<div id="aaa">
    <div id="sss">
    </div>
</div>

jQuery:

$('.qqq').on('click', function (e) {
    e.preventDefault();
    $('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
})
$('.auto_box').on('keyup change', '.de1', function () {
    alert('This is ok');
})

Try this like,

$('#sss').on('keyup change', '.auto_box .de1', function () {
    alert('This is ok');
});

Demo 1

Or

$('.qqq').on('click', function (e) {
    e.preventDefault();
    $('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');    
    // bind event here
    $('.auto_box').on('keyup change', '.de1', function () {
        alert('This is ok');
    });
});

Demo 2

Try:

$(document).on('keyup change', '.de1', function () {
    alert('This is ok');
});

Updated fiddle here.

replace '.auto_box' with document.

$(document).on('keyup change', '.de1', function () {
    alert('This is ok');
});

Reason:Why the above code works and yours does not?

1.You are dynamically adding elements.In simpler words,the element you appended did not exist when DOM was loaded.

2.You need to assign Event Delegation for any future addition of elements.The method that we usually use like .click(...) , .on(..) etc only applies to the elements that are currently in the DOM.

3.This is how you provide Event Delegation.

$( document ).on('keyup change', '.de1', function(){.........})

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