我有一个这样的 HTML 结构:
<div class="votes">
<b>5</b> Votes
<a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
</div>
我已经设法在 5 之后获得文本,即投票使用:
var voteTextNode = $(this).parent('div').contents().filter(function() {
return this.nodeType == 3;
});
var voteText = voteTextNode.text();
现在我想将此文本更改为投票,即各自的票数。我试过这个:
voteNewText = ( newCount == '1' ) ? 'Vote' : 'Votes';
voteTextNode.text(voteNewText);
但这对我不起作用。我也尝试过此链接中的代码: How can I get, manipulate and replace a text node using jQuery? 但它对我也不起作用告诉我哪里做错了
最佳答案
如您所见,jQuery 并不是真正为处理文本节点而设计的。您的 var voteTextNode
将是一个 jQuery 实例,包含一组文本节点。您几乎不能使用 .text()
操作它们,这会向它们添加一些新的 TextNode。
然而,这应该有效:
$(this).parent('div').contents().each(function() {
// iterate over all child nodes
if (this.nodeType == 3)
this.data = "Vote";
});
但是使用普通的 dom 方法可能会更清楚:
var countTextNode, voteTextNode;
$(this).parent('div').find('b').each(function() {
countTextNode = this.firstChild;
voteTextNode = this.nextSibling;
});
return function setVotes(num) {
countTextNode.data = num;
votTextNode.data = num == 1 ? 'Vote' : 'Votes';
};
关于javascript - 如何使用 jQuery 设置文本节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634719/