将JS重新应用于动态生成内容的最佳方式是什么?我说“重新应用JS”而不是“重新绑定事件”,因为a的意思是“重新应用绑定事件并更改dom的JS”,到目前为止我所做的事情是这样的:
main.js:
function repplyDynamic(){
$('.dynamic:not(.js-initialized)').each(function(){
$(this).addClass('js-initialized').append('<div class="chaging_dom"></div>').click(function(){
alert("Ae!");
});
});
}
other_code.js
$('body').append('<div id="dynamic">content</div>'); // could be a ajax call
reapplyDynamic();但我认为这非常混乱。你们有更好的方法吗?
发布于 2012-05-10 09:02:18
就我个人而言,我有一个名为dommods()的函数,它可以完成我需要的所有修改(工具提示、表单、自动调整文本大小等)。并在每次对DOM进行重要更改后调用它。
换句话说,这就是你正在做的事情,但是使用了不同的函数名。这没什么问题。
发布于 2012-05-10 09:02:46
可以使用jQuery's $().on method将事件处理程序附加到当前或将来的HTML元素。
发布于 2012-05-10 09:07:15
//main.js
function applyDynamicStuff(content){
return content //return content
.append('<div class="chaging_dom"></div>') //with appended element
.click(function(){ //with click hander
alert("Ae!");
});
}
//other_code.js
var dynamicItem = $('<div>content</div>') //the new content
applyDynamicStuff(dynamicItem).appendTo('body'); //apply Dynamic stuff and append to bodyhttps://stackoverflow.com/questions/10526194
复制相似问题