递归扫描DOM元素-Javascript

Recursively Scan DOM Elements - Javascript

本文关键字:-Javascript 元素 DOM 扫描 递归      更新时间:2023-09-26

我有以下html-

<a>
  <b>
   ....
    .....
    <input type="button" name="add" onclick="..." value="add another"/>
    </d>
   </b>
....
</a>

我使用以下js片段-

/**
 *  Dynamically add a remove button on next to the add button.
 *
 */
addRemoveButton = function(node) {
    if(node.nodeType == 3) {
        if(node.nodeName == "input") {
            if(node.getAttribute("type") == "button") {
                if(node.getAttribute("name") == "add") {
                    var removeButton = node.cloneNode(true);
                    removeButton.removeAttribute("name");
                    removeButton.setAttribute("value", "remove");
                    removeButton.setAttribute("onclick", "");
                    removeButton.setAttribute("id", "");
                    (node.parentNode).appendChild(removeButton);
                    return;
                }
            }
        }
    }
    if(node.nodeType == 1) {
        var list = node.childNodes;
        var i = 0;
        while(i<list.length) {
            return addRemoveButton(list[i]);
            i++;
        }
    }
    return;
}

现在,我想在上面列表中显示的当前按钮旁边添加一个类型为button的输入(remove button)。我试着递归地做这件事。但这是行不通的。你能在上面的代码中找到问题吗?

据我所知,您的代码还很差。您使用了错误的nodeType,nodeName的大小写也错误,没有理由使用大量嵌套的if语句。但是,你可以让它像这样递归地工作:

addRemoveButton = function(node) {
    if (node.nodeType == 1) {
        if (node.nodeName.toLowerCase() == "input" &&
          node.getAttribute("type") == "button" &&
          node.getAttribute("name") == "add") {
            var removeButton = node.cloneNode(true);
            removeButton.removeAttribute("name");
            removeButton.setAttribute("value", "remove");
            removeButton.setAttribute("onclick", "");
            removeButton.setAttribute("id", "");
            (node.parentNode).appendChild(removeButton);
            return;
        } else {
            var list = node.childNodes;
            for (var i=0; i < list.length; i++) {
                // be aware of childNodes changing on us live here
                // when we modify the DOM
                addRemoveButton(list[i]);
            }
        }
    }
}
addRemoveButton(document.body);

你可以在这里看到它的工作原理:http://jsfiddle.net/jfriend00/WCj4b/

使用jQuery(你也用它标记了你的问题)并继续使用克隆操作,你可以做到这一点:

$("input[type='button'][name='add']").each(function(index, el) {
    $(this).clone(false)
        .val("remove")
        .removeAttr("name")
        .attr("onclick", "")
        .attr("id", "")
        .insertAfter(this);
});

此处演示:http://jsfiddle.net/jfriend00/JKsZC/

或者一个简单得多的版本,只插入新的HTML,而不是克隆现有的按钮:

$("input[type='button'][name='add']").after('<input type="button" value="Remove" />');

此处演示:http://jsfiddle.net/jfriend00/vSZwp/

为什么是递归的?只是为了找到现有的按钮?让jQuery担心找到

$('input[type=button]').after("<input type='button' value='Remove' />");

调整这个按钮,让你的删除按钮做你需要的事情。