On 无法替代live;因为新的ON是为未来元素工作的NOT。我的实现没有问题;我习惯于使用live,我肯定知道jquery什么时候有效。
haml部分:
.field
%label Select a file
= file_field_tag 'post[image]', :class => :dashed
%span.adder + add another file
coffe部分:
$("span.adder").on "click", (e) ->
new_field = $(this).closest(".field").clone()
$(new_field).insertAfter( $(this).closest(".field") )
为什么添加的新span.adder没有将jquery行为附加到类中?这样的事情在那种情况下应该奏效。
为什么JQuery的人删除了它?我不明白。
更新
$("span.adder").on("click", function(){ });
不会像生活一样工作。
必须是
$(document).on("click", "span.adder", function(){ });
(感谢大家的回答。)
要处理未来的元素,您必须在像这样的文档上使用
$(document).on('click', 'span.adder', function(){
//Code here
});
在.on()
出现之前,.live()
已经被认为是处理事件绑定的低效方法,因此为了将来使用,您必须使用.on()
例如:-
$(document).on('click', '#yourElement', function() {
// your functions here
});
这里有更好的解释
它是一个替代品。直接翻译为:
$(document).on('click', '.my-selector', function() {});
他们反对并删除了它,因为他们有更好的实现。您可以看到.on()
的文档
$(ancestor).on(event, element, function);
您应该使用它作为靠近该元素的祖先。存在一些性能问题。
同时升级jQuery版本。
On
works as
委托`过去做过,不完全像.live;您必须在父级上使用它,然后指定触发它的事件和子级;类似的东西。
$(window).on("click", ".button", function(){
alert("You clicked the button... and I hate alerts");
});