jQuery在div上更改文本 [英] jquery change text on div

查看:96
本文介绍了jQuery在div上更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要更改div中的文本(其中有其他元素).我尝试了text方法,但它更改了div的全部内容.

I need to change only the text inside the div, where there is other elements inside it. I tried the text method but it changed the whole content of the div.

div示例:

<div class="mydiv">
MY TEXT HERE
<ul>
   <li>BLAH</li>
   <li>BLAH</li>
</ul>
</div>

这是我现在尝试过的:$(".mydiv").text("MY NEW TEXT");

This is what I have tried for now: $(".mydiv").text("MY NEW TEXT");

推荐答案

$.fn.extend({
    text2: function(t){
        return this.each(function(a,b){
            $(b).contents().map(function(c,d){
                return (d.nodeType === 3 ? d : null);
            }).get(0).data = t;
        });
    }
});

有我的解决方案.仅影响选择器中找到的 first 文本节点,然后将其替换为提供的文本.使用此功能,$('.mydiv').text2('MY NEW TEXT');应该完美.

There's my solution. Only effects the first text node found within the selector, then replaces it with the supplied text. Using this, $('.mydiv').text2('MY NEW TEXT'); should work flawlessly.

这篇关于jQuery在div上更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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