如何捕获DOM元素的创建并使用jQuery操作它们

时间:2011-02-06 18:57:16

标签: javascript jquery events dom

我正在尝试设计一种方法,在添加一个带有类和一些data- *的简单div元素时,它将替换它或添加一些其他元素。不应该手动调用此方法,而是通过某种.live()jQuery方法,自定义事件或类似$('body')。bind('create.custom')等自动调用此方法。 我需要这种方式,因为我事先不知道将创建哪些元素,因为它们将通过像单个空div或p的ajax一样提供。

<!DOCTYPE html>
<html>
    <head>

        <title >on create</title>

        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>

        <script type="text/javascript" >

            jQuery(function($){
                $("div.fancyInput").each(function(index,element){

                    var $div = $(this);
                    var dataId = $div.attr("data-input-id");
                    var inputId = '';
                    var labelId = '';
                    if(!!dataId){
                        inputId = 'id="' + dataId + '"';
                        labelId = 'id="' + dataId + 'Label"';
                    } // if

                    var dataValue = $div.attr();

                    $(
                        '<p class="fancyInput" >' +
                        '    <label ' + labelId + ' for="' + inputId + '" >A fancy input</label>' +
                        '    <input ' + inputId + ' name="' + inputId + '" value="A fancy input" />' +
                        '</p>'
                    ).appendTo($div);               
                }); // .each()
            }); // jQuery()
        </script>

        <script type="text/javascript" >

            jQuery(function($){
                var counter = 2;
                var $form = $('#form');
                $('#add').click(function(event){
                    $('<div class="fancyInput" data-input-id="fancyInput' + counter + '" ></div>').appendTo($form);
                    counter++;
                }); // .click
            }); // jQuery()

        </script>
    </head>
    <body>

        <a id="add" href="#" > add another one </a>
        <form id="form" action="#" >

            <p class="normalInput" >
                <label id="normalInputLabel" for="normalInput" >A normal input</label>
                <input id="normalInput" name="normalInput" value="A normal input" />
            </p>

            <div class="fancyInput" ></div>

        </form>
    </body>
</html>

更新 我事先检查了liveQuery,它是我需要的那种功能,但能够在执行事件回调时修改DOM元素。所以这不仅仅是我需要附加事件,而是在元素创建时修改DOM的能力。例如:每当创建一个new时,它应该用p,label和input标签填充(如果更换,则更好)

1 个答案:

答案 0 :(得分:4)

您可以使用DOM级别3事件,例如DOMNodeInserted。这看起来像是:

$(document).bind('DOMNodeInserted', function(event) {
    // A new node was inserted into the DOM
    // event.target is a reference to the newly inserted node
});

作为替代方案,您可以查看.liveQueryhelp jQuery插件。

<强>更新

参考你的评论,看一下http://www.quirksmode.org/dom/events/index.html,只有不支持它的浏览器才是这个世界的互联网探索者(我猜IE9至少会这样做)。

我不能多说性能,但它应该表现得相当不错。