【问题标题】:jQuery text Node Object to stringjQuery文本节点对象到字符串
【发布时间】:2012-03-08 10:32:53
【问题描述】:

我正在使用此代码:

/**
 * Get Text Nodes from an Element
 * Returns and object unless number is passed in
 * Numbers is 0 based
 */
(function( $ ) {
$.fn.textNodes = function(number) {
    var nodes = jQuery(this).contents().filter(function(){
        return this.nodeType == 3;
    });
    if(jQuery.isNumber(number)){
        return nodes[number];
    }
    return nodes;
};
})( jQuery );

用于从html中抓取文本节点

例如:

<div>
    <span>Testing</span>
    What is this?
</div>

我在找What is this?

这很有效,因为我可以创建一个 console.log 并在控制台中查看结果。

但是当我尝试在输入字段中使用结果时,它给了我:[object Text]

如何将结果用作字符串值?

我尝试过 toString() ,但结果相同,除非我错过了什么。

【问题讨论】:

    标签: javascript jquery text


    【解决方案1】:

    使用nodeValue 属性:

    $("#yourInputField").val(yourTextNode.nodeValue);
    

    【讨论】:

    • 这是我问题的正确答案。我喜欢 thg435 给出的旋转。谢谢!
    【解决方案2】:

    您的代码可以工作,但它没有使用 jQuery 的优点。怎么样:

    (function($) {
        $.expr[':'].textnode = function(element) {
            return element.nodeType == 3;
        }
    
        $.valHooks["#text"] = { get: function(elem) {
            return $.trim(elem.nodeValue);
        }}
    
    })(jQuery)
    

    这样使用:

    lastText = $("div").contents(":textnode:last").val()
    

    http://jsfiddle.net/YXjEB/

    【讨论】:

      【解决方案3】:

      当您需要实际使用文本时,您会收到作为 DOM 对象的文本节点:textContentnodeValue

      jsFiddle

      【讨论】:

      • textContent 未在旧版浏览器中实现,包括 IE nodeValue 或 data,这两种浏览器都适用于所有主流浏览器。
      猜你喜欢
      • 2015-08-10
      • 1970-01-01
      • 2019-05-09
      • 2015-12-24
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      相关资源
      最近更新 更多