现在我正在学习 Node 。在此之前,如果我的问题不具体,请让我知道如何更好地表达,我很抱歉。
此代码用于删除元素属性。 表格列中有一种颜色,当我按下按钮时,td 标记中的属性 bgcolor 消失了。
当我运行它时,它总是显示tdelement
为空?虽然我已经使用 for 语句来循环并检查它。
请使用Javascript回答。
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttribute("value");
//If the attribute matches the color then delete attributes
if (colorAtt == color)
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
// the end for javascript -----------------
<table id="multi" border="1">
<tr>
<td></td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#ff0000">1</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#ffff00">3</td>
</tr>
<tr>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">2</td>
<td bgcolor="#008000">4</td>
<td bgcolor="#ffff00">6</td>
</tr>
<tr>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">3</td>
<td bgcolor="#ffff00">6</td>
<td bgcolor="#ffff00">9</td>
</tr>
</table>
<button onclick="removeColor('#ff0000')">Remove Red Background</button><br>
最佳答案
试试这个
function removeColor(color)
{
var table = document.getElementById("multi");
var tdList = table.getElementsByTagName("td");
// Loop through list <td> elements.
for (var i = 0; i <= tdList.length; i++)
{
var tdElement = tdList.item(i);
// Get the attribute.
var colorAtt = tdElement.getAttributeNode("bgcolor");
//If the attribute matches the color then delete attributes
if (colorAtt && (colorAtt.value == color))
{
tdElement.removeAttributeNode(colorAtt);
}
}
}
using .getAttribute("value");
将尝试从元素获取属性“value”。您需要在其中获取 Node .getAttributeNode("bgcolor");
。
关于javascript - 无法在 Javascript 中使用 getAttribute() 从表中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943703/