下面的代码我正在使用表格中的删除单元格(已选中).它在某些时候有效,但有时候会出现"未找到节点"的代码:
"8"(NS_ERROR_DOM_NOT_FOUND_ERR)
似乎无法想象如何做到这一点.任何帮助都会很棒.
var p = document.getElementById('tableTr');
while(selectTag=document.getElementsByClassName('tagSelected')) {
if(!selectTag[0]) {
break;
}
if(selectTag[0].className=="tagSelected")
var c =selectTag[0];
p.removeChild(c);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个填充表格的PHP脚本,以及关于它的HTML脚本:
<div id="uploadTag">
<table class="tagBlock" id="tableTag" cellspacing="5px;">
<?php
$uploadlist=substr($uploadlists, 0, -1);
$uploadList=explode(";",$uploadlist);
$i=0;
foreach($uploadList as $key=>$list){
if($i==0)
{ ?>
<tr id="tableTr">
<?php }
$i++; $up="up".($key+1);
$imageext = substr(strrchr($list, '.'), 1);
$val=$list;
if ($imageext=='png' || $imageext=='bmp' || $imageext=='gif' || $imageext=='tif' || $imageext=='jpg')
{
$val="<image>";
}
?><td id="<?php echo $up; ?>" class="tagBlock" title="<?php echo $list; ?>"><div id="<?php echo $up; ?>" class="tagBlockW" title="<?php echo $list; ?>"><?php echo "$val"; ?></div></td> <?php
if($i==7){ $i=0;?> </tr> <?php }?>
<?php }
?>
</tr>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
Rig*_*red 10
这里有一些问题.
它无效,会产生意想不到的结果.要么使用类,要么使ID唯一.
DOM选择是一项昂贵的操作.它应该在循环外执行一次,然后缓存.
tagSelected循环内的类.你使用过getElementsByClassName('tagSelected'),显然他们有那个班级.
您似乎只想删除给定类的元素.
// Fetch all elements in the document with the class 'tagSelected'
var selectTag = document.getElementsByClassName('tagSelected');
// Remove all of them.
while( selectTag[0] ) {
selectTag[0].parentNode.removeChild( selectTag[0] );
}
Run Code Online (Sandbox Code Playgroud)
有效的原因while( selectTag[0] ) {是getElementsByClassName返回"实时"NodeList.这意味着当从DOM中删除元素时,列表会更新.
因为我们正在删除所有元素,所以我们需要做的只是在索引处有一些东西时运行循环[0].