我有一个使用 jquery 向 DOM 添加和删除输入的页面。其中一些共享一个类(“数字”)。附加每个输入后,我的代码应该使用“numeric”类对每个新输入调用 .numeric() 。我在代码的开头定义了这个 block ,
$('input.numeric')
.live('load', function() {
$(this).numeric();
});
但是在加载 DOM 后,加载似乎与附加节点无关。就绪事件也不起作用。
我怎样才能做到这一点?谢谢各位 friend
编辑:我设法以更通用的方式解决了以下@BGerrissen方法。我已经定义了一个用于附加的包装器(我称之为绘制),然后每次附加任何内容时,我都会触发 $(document).trigger('appished')
,因此很容易在任何地方进行跟踪。然后我使用
$(document)
.bind('appended', function() {
$('input.numeric').numeric();
});
做我需要做的事。干杯
最佳答案
附加输入时,也会触发自定义事件。
var child = $("<input class='numeric' />");
$("#parent").append(child);
child.trigger("appended");
然后您可以将事件 Hook 以达到您的目的:
$('input.numeric')
.live('appended', function() { // Use .on() method from jQuery 1.7 and up
$(this).numeric();
});
注意:从 jQuery 1.7 开始,.live() 已被弃用。使用.on()
或者使用辅助方法在附加时触发事件。
function appendAndFireAppendEvent( parentExpr , childExpr ){
var child = $( childExpr );
$( parentExpr ).append(child);
child.trigger("appended");
}
// usage
appendAndFireAppendEvent( "#parentElement" , "<input class='numeric' />" );
不建议**
您还可以重写 jQuery 的append() 方法以始终触发“附加”事件。
var oldAppend = $.fn.append;
$.fn.append = function( el )
{
oldAppend.call( this , el ); // DONT convert el to a JQuery object before passing it to oldAppend
$(el).trigger("appended");
return $(el); // to allow chaining to work
}
但这将适用于所有append()调用,无论您是否想要它,并且可能会破坏某些东西,因为我没有调查此覆盖的稳定性。
关于javascript - 使用 jQuery 将输入附加到 DOM 时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075539/