ฉันต้องการรับโหนดข้อความที่สืบทอดทั้งหมดขององค์ประกอบเป็นคอลเลกชัน jQuery วิธีที่ดีที่สุดในการทำเช่นนั้นคืออะไร?
ฉันต้องการรับโหนดข้อความที่สืบทอดทั้งหมดขององค์ประกอบเป็นคอลเลกชัน jQuery วิธีที่ดีที่สุดในการทำเช่นนั้นคืออะไร?
คำตอบ:
jQuery ไม่มีฟังก์ชั่นอำนวยความสะดวกสำหรับสิ่งนี้ คุณต้องรวมcontents()ซึ่งจะให้เพียงโหนดลูก แต่รวมถึงโหนดข้อความด้วยfind()ซึ่งจะให้องค์ประกอบลูกหลานทั้งหมด แต่ไม่มีโหนดข้อความ นี่คือสิ่งที่ฉันเกิดขึ้น:
var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};
getTextNodesIn(el);
หมายเหตุ: หากคุณใช้ jQuery 1.7 ขึ้นไปรหัสข้างต้นจะไม่ทำงาน ในการแก้ไขปัญหานี้แทนด้วยaddBack() เลิกใช้แล้วตั้งแต่ 1.8 เป็นต้นไปandSelf()andSelf()addBack()
นี้จะค่อนข้างไม่มีประสิทธิภาพเมื่อเทียบกับวิธี DOM ที่บริสุทธิ์และมีการรวมถึงการแก้ปัญหาที่น่าเกลียดสำหรับการบรรทุกเกินพิกัดของ jQuery ของcontents()ฟังก์ชั่น (ขอบคุณ @rabidsnail ในการแสดงความคิดเห็นสำหรับการชี้ให้เห็นว่า) ดังนั้นนี่คือไม่ใช่ jQuery วิธีการแก้ปัญหาโดยใช้ฟังก์ชันเวียนง่าย includeWhitespaceNodesควบคุมพารามิเตอร์หรือไม่ว่าช่องว่างโหนดข้อความที่จะถูกรวมในการส่งออก (ใน jQuery พวกเขาจะถูกกรองออกโดยอัตโนมัติ)
ปรับปรุง: แก้ไขข้อผิดพลาดเมื่อ includeWhitespaceNodes เป็นเท็จ
function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /\S/;
    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }
    getTextNodes(node);
    return textNodes;
}
getTextNodesIn(el);
              document.getElementById()ก่อนได้ถ้านั่นคือสิ่งที่คุณหมายถึง:var div = document.getElementById("foo"); var textNodes = getTextNodesIn(div);
                    .contents()anyways ก็หมายความว่ามันจะค้นหา iframe ด้วยเช่นกัน ฉันไม่เห็นว่ามันอาจจะเป็นข้อผิดพลาด
                    Jauco โพสต์คำตอบที่ดีในความคิดเห็นดังนั้นฉันจึงคัดลอกที่นี่:
$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });
              $('body').find('*').contents().filter(function () { return this.nodeType === 3; });
              jQuery.contents()สามารถใช้กับjQuery.filterการค้นหาโหนดข้อความลูกทั้งหมด คุณสามารถค้นหาโหนดข้อความของลูกหลานได้เช่นกัน ไม่จำเป็นต้องทำการสอบถามซ้ำ:
$(function() {
  var $textNodes = $("#test, #test *").contents().filter(function() {
    return this.nodeType === Node.TEXT_NODE;
  });
  /*
   * for testing
   */
  $textNodes.each(function() {
    console.log(this);
  });
});
div { margin-left: 1em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
  child text 1<br>
  child text 2
  <div>
    grandchild text 1
    <div>grand-grandchild text 1</div>
    grandchild text 2
  </div>
  child text 3<br>
  child text 4
</div>
ฉันได้รับโหนดข้อความว่างเปล่าจำนวนมากพร้อมฟังก์ชันตัวกรองที่ยอมรับได้ หากคุณสนใจเพียงในการเลือกโหนดข้อความที่มีไม่ใช่ช่องว่างลองเพิ่มnodeValueเงื่อนไขของfilterฟังก์ชั่นที่เรียบง่ายเช่น$.trim(this.nodevalue) !== '':
$('element')
    .contents()
    .filter(function(){
        return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
    });
หรือเพื่อหลีกเลี่ยงสถานการณ์แปลก ๆ ที่เนื้อหาดูเหมือนช่องว่าง แต่ไม่ใช่ (เช่น­อักขระยัติภังค์อ่อนบรรทัดใหม่\nแท็บ ฯลฯ ) คุณสามารถลองใช้นิพจน์ปกติได้ ตัวอย่างเช่น\Sจะจับคู่อักขระที่ไม่ใช่ช่องว่าง:
$('element')
        .contents()
        .filter(function(){
            return this.nodeType === 3 && /\S/.test(this.nodeValue);
        });
              หากคุณสามารถสันนิษฐานได้ว่าเด็กทุกคนเป็นองค์ประกอบโหนดหรือโหนดข้อความนี่คือทางออกหนึ่ง
ในการรับโหนดข้อความลูกทั้งหมดเป็นคอลเลกชัน jquery:
$('selector').clone().children().remove().end().contents();
ในการรับสำเนาขององค์ประกอบดั้งเดิมโดยไม่ต้องใช้ลูกที่ไม่ใช่ข้อความให้ทำดังนี้
$('selector').clone().children().remove().end();
              ด้วยเหตุผลบางอย่างcontents()ไม่ได้ผลสำหรับฉันดังนั้นถ้ามันไม่ได้ผลสำหรับคุณนี่เป็นวิธีแก้ปัญหาที่ฉันทำฉันสร้างขึ้นjQuery.fn.descendantsด้วยตัวเลือกเพื่อรวมโหนดข้อความหรือไม่
การใช้
รับการสืบทอดทั้งหมดรวมถึงโหนดข้อความและโหนดองค์ประกอบ
jQuery('body').descendants('all');
รับการสืบทอดทั้งหมดที่ส่งคืนเฉพาะโหนดข้อความ
jQuery('body').descendants(true);
รับการสืบทอดทั้งหมดที่ส่งคืนเฉพาะโหนดองค์ประกอบ
jQuery('body').descendants();
ต้นฉบับกาแฟ :
jQuery.fn.descendants = ( textNodes ) ->
    # if textNodes is 'all' then textNodes and elementNodes are allowed
    # if textNodes if true then only textNodes will be returned
    # if textNodes is not provided as an argument then only element nodes
    # will be returned
    allowedTypes = if textNodes is 'all' then [1,3] else if textNodes then [3] else [1]
    # nodes we find
    nodes = []
    dig = (node) ->
        # loop through children
        for child in node.childNodes
            # push child to collection if has allowed type
            nodes.push(child) if child.nodeType in allowedTypes
            # dig through child if has children
            dig child if child.childNodes.length
    # loop and dig through nodes in the current
    # jQuery object
    dig node for node in this
    # wrap with jQuery
    return jQuery(nodes)
วางในเวอร์ชัน Javascript
var __indexOf=[].indexOf||function(e){for(var t=0,n=this.length;t<n;t++){if(t in this&&this[t]===e)return t}return-1}; /* indexOf polyfill ends here*/ jQuery.fn.descendants=function(e){var t,n,r,i,s,o;t=e==="all"?[1,3]:e?[3]:[1];i=[];n=function(e){var r,s,o,u,a,f;u=e.childNodes;f=[];for(s=0,o=u.length;s<o;s++){r=u[s];if(a=r.nodeType,__indexOf.call(t,a)>=0){i.push(r)}if(r.childNodes.length){f.push(n(r))}else{f.push(void 0)}}return f};for(s=0,o=this.length;s<o;s++){r=this[s];n(r)}return jQuery(i)}
รุ่น Javascript ที่ไม่ระบุ: http://pastebin.com/cX3jMfuD
นี่คือ cross browser, Array.indexOfpolyfill ขนาดเล็กรวมอยู่ในรหัส
สามารถทำได้เช่นนี้
var textContents = $(document.getElementById("ElementId").childNodes).filter(function(){
        return this.nodeType == 3;
});
รหัสด้านบนกรอง textNodes จากโหนดลูกย่อยโดยตรงขององค์ประกอบที่กำหนด
หากคุณต้องการตัดแท็กทั้งหมดให้ลองใช้งาน
ฟังก์ชั่น:
String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}
การใช้งาน:
var newText=$('selector').html().stripTags();
              สำหรับฉันธรรมดาเก่า .contents()ดูเหมือนจะทำงานเพื่อส่งกลับโหนดข้อความเพียงแค่ต้องระมัดระวังกับตัวเลือกของคุณเพื่อให้คุณรู้ว่าพวกเขาจะเป็นโหนดข้อความ
ตัวอย่างเช่นสิ่งนี้ห่อเนื้อหาข้อความทั้งหมดของ TD ในตารางของฉันด้วยpreแท็กและไม่มีปัญหา
jQuery("#resultTable td").content().wrap("<pre/>")
              ฉันมีปัญหาเดียวกันและแก้ไขด้วย:
รหัส:
$.fn.nextNode = function(){
  var contents = $(this).parent().contents();
  return contents.get(contents.index(this)+1);
}
การใช้งาน:
$('#my_id').nextNode();
เป็นเหมือนnext()แต่ยังส่งคืนโหนดข้อความ