将JS重新应用于动态生成的内容

时间:2012-05-10 00:58:51

标签: javascript jquery dynamic-rebinding

将JS重新应用于动态生成内容的最佳方法是什么?我说“重新应用JS”而不是“重新绑定事件”,因为意味着“重新应用JS来绑定事件并改变dom”,到目前为止我所做的就是这样:

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();

但我认为这非常混乱。你们有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

就我个人而言,我有一个名为dommods()的函数,可以完成我需要的所有修改(工具提示,表单,自动调整文本等),并在每次对DOM进行重大更改后调用它。

换句话说,正是你在做什么,但使用不同的功能名称。它没有错。

答案 1 :(得分:0)

您可以使用jQuery's $().on method将事件处理程序附加到当前或未来的HTML元素。

答案 2 :(得分:0)

//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 body
相关问题