jquery - 获取没有子文本的元素的文本

jquery  - 获取没有子文本的元素的文本

问题描述:

例如我们有这个文件

<div id="mydiv">
    some text here 
    <div id="inner div">
         text for inner div
    </div>
</div>

我需要 #mydiv 仅限文字使用这样的代码:

i need to get #mydiv text only with some code like this :

alert($('#mydiv').text());  // will alert "some text here"


嘿试试请: http://jsfiddle.net/MtVxx/2/

此处您的具体案例的良好链接: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ (这只会获取元素的文本)

Good link for your specific case in here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ (This will only get the text of the element)

希望这有帮助,:)

代码

jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

alert($('#mydiv').justtext());​