Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - 在jQuery中将live()转换为on()(Turning live() into on() in jQuery)

My application has dynamically added Dropdowns.(我的应用程序动态添加了Dropdown。)

The user can add as many as they need to.(用户可以根据需要添加任意数量的内容。)

I was traditionally using jQuery's live() method to detect when one of these Dropdowns was change() ed:(我传统上使用jQuery的live()方法来检测其中一个Dropdowns是否为change() ed:)

$('select[name^="income_type_"]').live('change', function() {
    alert($(this).val());
});

As of jQuery 1.7, I've updated this to:(从jQuery 1.7开始,我将其更新为:)

$('select[name^="income_type_"]').on('change', function() {
    alert($(this).val());
});

Looking at the Docs, that should be perfectly valid (right?) - but the event handler never fires.(看看Docs,这应该是完全有效的(对吗?) - 但事件处理程序永远不会触发。)

Of course, I've confirmed jQuery 1.7 is loaded and running, etc. There are no errors in the error log.(当然,我已经确认jQuery 1.7已加载并正在运行等。错误日志中没有错误。)

What am I doing wrong?(我究竟做错了什么?)

Thanks!(谢谢!)   ask by Jack translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The on documentation states (in bold ;)):(on文档说明(粗体;)):)

Event handlers are bound only to the currently selected elements;(事件处理程序仅绑定到当前选定的元素;)

they must exist on the page at the time your code makes the call to .on() .(它们必须存在于您的代码调用.on() 。)

Equivalent to .live() would be something like(相当于.live()就像是)

$(document.body).on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

Although it is better if you bind the event handler as close as possible to the elements, that is, to an element being closer in the hierarchy.(尽管将事件处理程序尽可能地绑定到元素(即,更靠近层次结构中的元素)会更好。)

Update: While answering another question, I found out that this is also mentioned in the .live documentation :(更新:在回答另一个问题时,我发现.live文档中也提到了这一点:)

Rewriting the .live() method in terms of its successors is straightforward;(根据其后继者重写.live()方法很简单;)

these are templates for equivalent calls for all three event attachment methods:(这些是用于所有三种事件附件方法的等效调用的模板:)
 $(selector).live(events, data, handler); // jQuery 1.3+ $(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ $(document).on(events, selector, data, handler); // jQuery 1.7+ 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...