如何使用jQuery设置文本节点值 [英] How to set the text node value using jQuery

查看:53
本文介绍了如何使用jQuery设置文本节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的HTML结构:

I have a HTML structure like this:

<div class="votes">
    <b>5</b> Votes
    <a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
</div>

我设法使用以下方法在5个投票后获得了文本:

I have manage to get the text after 5 i.e. votes using:

var voteTextNode = $(this).parent('div').contents().filter(function() {
                    return this.nodeType == 3;  
                });
var voteText = voteTextNode.text();

现在我想将此文本更改为投票,这是各自的投票数.我已经尝试过了:

now i want to change this text to vote which is respective number of votes . I have tried this:

voteNewText = ( newCount == '1' ) ? 'Vote' : 'Votes';
voteTextNode.text(voteNewText);

但这对我不起作用.我也尝试过此链接中的代码:如何获取,操作和替换使用jQuery的文本节点?但这对我也不起作用,告诉我我在哪里做错了

but it does not work for me. I have also tried the code from this link: How can I get, manipulate and replace a text node using jQuery? but it also wont work for me tell me where i am doing wrong

推荐答案

将其放在跨度中

<div class="votes">
    <b>5</b> <span id="votesTxt">Votes</span>
    <a id="vote-' + element_id +'" href="#" class="vote-btn"></a>
</div>

然后

$("#votesTxt").text(( newCount == '1' ) ? 'Vote' : 'Votes');


编辑,如果您不想使用跨度,则只需在b标记后更改元素的文本即可:


EDIT if you don't wish to use span then just change the text for the element after the b tag:

$("#votes b:first")[0].nextSibling.data = (( newCount == '1' ) ? 'Vote' : 'Votes');

这篇关于如何使用jQuery设置文本节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆