简体   繁体   English

追加后不工作我的jQuery代码

[英]Don't work my jQuery code after append

Don't work my jQuery code after append. 追加后不要使用我的jQuery代码。 how can just change js code and worked it? 怎样才能更改js代码并使其起作用?

I don't use from ides "#aaa or #sss", How do without use them? 我不使用ide“ #aaa或#sss”,如何不使用它们呢?

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

html: HTML:

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

jQuery: 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 演示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 演示2

Try: 尝试:

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

Updated fiddle here. 在这里更新了小提琴。

replace '.auto_box' with document. 用文档替换'.auto_box'

$(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. 1.您正在动态添加元素。简单来说,加载DOM时,您添加的元素不存在。

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. 2,您需要为将来添加任何元素分配事件委托 。我们通常使用的方法如.click(...) , .on(..)等仅适用于DOM中当前存在的元素。

3.This is how you provide Event Delegation. 3.这就是您提供事件委托的方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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