如何在文字后设置文字样式?

时间:2017-08-29 16:32:00

标签: javascript jquery

我正在尝试使用clone()并且我接近它但我无法替换文本,它显示了两者:



var td_clone = $('.ms-vb').clone();
$('span', td_clone).remove();
$('br', td_clone).remove();
var name = $.trim(td_clone.text());
$("td").append(name.toUpperCase());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
    <tr>
        <td width="80%" style="padding-bottom: 3px" class="ms-vb">
            <span class="ms-announcementtitle">
                title is here
            </span>
            <br>
            by hey
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

结果:

title is here 
by hey BY HEY

虽然我期待:

title is here 
BY HEY

jsFiddle here

3 个答案:

答案 0 :(得分:3)

您没有正确执行此操作,只需直接定位textNode

&#13;
&#13;
var node = document.querySelector('.ms-vb br').nextSibling;

node.textContent = node.textContent.toUpperCase();
&#13;
<table>
    <tr>
        <td width="80%" style="padding-bottom: 3px" class="ms-vb">
            <span class="ms-announcementtitle">
                title is here
            </span>
            <br>
            by hey
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

更多jQuery&#39; ish将使用contents(),它实际上返回注释和文本节点,但是当普通JS解决方案如此简单时,真的不需要这样做,并且jQuery版本包含几乎相同的用于设置文本的代码

$('.ms-vb').contents().each(function() {
    if (this.nodeType === 3) 
        this.textContent = this.textContent.toUpperCase();
});

答案 1 :(得分:2)

您需要先从td删除文字,您可以执行以下操作:

&#13;
&#13;
var td_clone = $('.ms-vb').clone();
var elements = $('.ms-vb').children();
$('span', td_clone).remove();
$('br', td_clone).remove();
$('.ms-vb').html('');
$('.ms-vb').append(elements);
var name = $.trim(td_clone.text());
$("td").append(name.toUpperCase());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
    <tr>
        <td width="80%" style="padding-bottom: 3px" class="ms-vb">
            <span class="ms-announcementtitle">
                title is here
            </span>
            <br>
            by hey
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这应该这样做

var td_clone = $('.ms-vb').clone();
console.log(td_clone);
$('span', td_clone).remove();
$('br', td_clone).remove();
var name = $.trim(td_clone.text());
$("td").append(name.toUpperCase());