不要使用.eq(1)[0]
,而只是.get(0)
为了获取普通的 DOM 节点。另外,不要使用两种不同的方式来获取相同的文本节点,而只能使用一种方式并将其存储在变量中。让我们检查一下发生了什么:
$('.my-table tr').each(function() {
var cell = $('td', this);
if (!cell.length)
return alert("Could not find a table cell");
var el = cell.get(0);
if (!el) alert("Could not get first element"); // Won't happen if length was >0
if (!el.childNodes.length)
return alert("Cell is empty!");
var text = el.childNodes[0];
if (cell.contents()[0] != text) alert("different firstChilds???"); // Won't happen
if (text.nodeType != 3)
return alert("the first child node is not a text node!");
var contact = text.nodeValue;
if (text.data != contact) alert("different contents???"); // Won't happen
if (typeof contact != "string") alert("content is no string"); // Won't happen
var newcontact = contact.substring(0,10);
alert('"'+contact+'" was changed to "'+newcontact+'"');
text.data = newcontact;
});
(在 jsfiddle.net 上的演示)