递归扫描DOM元素-Javascript
Recursively Scan DOM Elements - Javascript
我有以下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' />");
调整这个按钮,让你的删除按钮做你需要的事情。
相关文章:
- 如何找到Javascript元素的最长边
- 如何通过它瞄准javascript元素's的onclick属性
- Javascript元素相对于屏幕的位置
- 找不到javascript元素
- JavaScript元素遍历返回的值超出预期
- 没有获得基础's的Javascript元素工作(与Laravel和Elixir)
- 为什么在ASP.NET Ajax更新面板中执行任何操作后javascript元素都停止工作
- 将 JavaScript 元素 ID 传递给 PHP 或 Form Variable
- Javascript元素相互阻塞
- CefSharp javascript元素点击不;不起作用,但手动点击它可以
- javascript元素.click()发布Safari
- Javascript元素更新侦听器
- Javascript 元素值的总和
- 在 php 代码中调用 javascript 元素
- If-Statement中的Javascript元素验证
- JavaScript 元素识别和检索
- 单击内部锚点/哈希时自动更新 JavaScript 元素
- 将 JavaScript 元素作为变量传递
- 按下表单重置按钮时删除 JavaScript 元素
- 将 javascript 保留在新的 JavaScript 元素中