2010-04-13 17 views
4

我在jQuery對象中有一段html。當我說$(本)。html的()我得到:獲取封裝在jquery對象中的html元素的直接內容

<span class="value">4</span><span class="type">teaspoons</span>butter 

我想只有從這個HTML代碼段是不跨接中的一段文字。在這個例子中,它是黃油。

我該怎麼做?

謝謝!

+1

http://stackoverflow.com/questions/1476787/jquery-innertext-not-including-sub-element – R0MANARMY 2010-04-13 03:53:58

+0

也基本相同問題的可能的複製:http://stackoverflow.com/que stions/2775893 /如何獲取文本中的任何其他容器的一部分 - jquery/3003950#3003950 – gnarf 2010-06-09 07:54:27

回答

1

有容易的,但欺騙的方式,放下所有的孩子,得到的文本屬性

var tmp = $(".post-text").clone(); 
tmp.children().remove(); 
tmp.text(); 

編輯還有一個Text Children plugin做這個。

0
var textvalues = $(this).contents().map(function() { 
    return this.nodeType === 3 ? this.nodeValue : null; 
}); 
+1

不是真的,你可以使用'.contents()':) – gnarf 2010-06-09 07:32:59

+0

在'contents'函數處改變@ gnarf的指針。 – wombleton 2010-06-10 02:03:56

0

此示例使用.contents()讓所有的子節點(包括文本節點),然後使用.map()把每個子節點爲基礎的nodeType的字符串。如果節點是文本節點(即文本不在跨度範圍內),我們將返回它的nodeValue

返回一個包含字符串的jQuery集合,所以我們調用.get()來獲得一個'標準'數組對象,我們可以調用.join()

// our 'div' that contains your code: 
var $html = $('<div><span class="value">4</span><span class="type">teaspoons</span>butter</div>'); 

// Map the contents() into strings 
$html.contents().map(function() { 
    // if the node is a textNode, use its nodeValue, otherwise empty string 
    return this.nodeType == 3 ? this.nodeValue : ''; 
    // get the array, and join it together: 
}).get().join(''); 

// "butter" 

如果你需要做這個有很多,你可以做一個快捷插件:

$.fn.directText = function() { 
    return this.contents().map(function() { 
    return this.nodeType == 3 ? this.nodeValue : ''; 
    }).get().join(''); 
}; 

或支持提一個稍微更強大的版本空白/改變,它連接結果陣列文本搭配:

$.fn.directText = function(settings) { 
    settings = $.extend({},$.fn.directText.defaults, settings); 
    return this.contents().map(function() { 
    if (this.nodeType != 3) return undefined; // remove non-text nodes 
    var value = this.nodeValue; 
    if (settings.trim) value = $.trim(value); 
    if (!value.length) return undefined; // remove zero-length text nodes 
    return value; 
    }).get().join(settings.joinText); 
}; 

$.fn.directText.defaults = { 
    trim: true, 
    joinText: '' 
};