jQuery的.text()在内部是如何工作的? [英] How does jQuery’s .text() work, internally?
问题描述
我很快就试图在jQuery的源代码中找到实现,但只找到这个实际上似乎并没有完全定义它。
I quickly tried to find the implementation in jQuery’s source, but only found this which doesn’t actually seem to define it completely.
来自jQuery源
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function() {
return jQuery(this).text( text.call(this) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.getText( this );
},
任何人都知道吗?
澄清:
我知道如何使用它。我只是想知道当jQuery不可用时如何获取jQuery元素的文本。
Clarification:
I know how to use it. I just want to know how to get the text of an element à la jQuery when jQuery isn’t available.
推荐答案
jQuery。 fn.text可以用于3种不同的目的,因为您粘贴的源清楚地显示。您正在寻找的案例是第三个 - 返回元素的文本值。
jQuery.fn.text can be used for 3 different purposes, as the source you pasted clearly shows. The case you're looking for, is the third one - returning the text value of an element.
jQuery使用jQuery.text()方法获取文本值一个元素,jQuery.text指向Sizzle.getText()
jQuery uses jQuery.text() method to get the text value of an element, and jQuery.text points to Sizzle.getText()
jQuery.text = Sizzle.getText;
这里是getText函数的定义。
And here's the definition of getText function.
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
工作示例: http ://jsfiddle.net/cBsDN/
这篇关于jQuery的.text()在内部是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!