Cod*_*ank 2 html javascript string jquery
我有这样的 HTML 结构:
<div class="votes">
<b>5</b> Votes
<a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
</div>
Run Code Online (Sandbox Code Playgroud)
我已经设法在 5 次投票后使用以下方法获得文本:
var voteTextNode = $(this).parent('div').contents().filter(function() {
return this.nodeType == 3;
});
var voteText = voteTextNode.text();
Run Code Online (Sandbox Code Playgroud)
现在我想更改此文本以投票,即各自的票数。我试过这个:
voteNewText = ( newCount == '1' ) ? 'Vote' : 'Votes';
voteTextNode.text(voteNewText);
Run Code Online (Sandbox Code Playgroud)
但这对我不起作用。我还尝试了此链接中的代码: 如何使用 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";
});
Run Code Online (Sandbox Code Playgroud)
但是使用普通的 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';
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11335 次 |
| 最近记录: |