2017-04-14 25 views
0

我試圖實現自己的脫字符號,當它在文本的開頭,並且轉到左邊時,它應該轉到DOM中的前一個文本節點。我的問題是,這並不總是我可以輕鬆找到的以前的兄弟姐妹。它可能是它在父母的兄弟姐妹的樹的底部。這應該澄清我的問題:如何獲取在給定之前顯示的前一個文本節點?

function getPreviousTextElement(node) { 
 
var prev = $('.caret').closest(':text'); 
 
prev.css('color', 'green'); 
 
}
#carot{ 
 
    color:red; 
 
}
<div> 
 
1 <div> 
 
    2 
 
    <div>3</div> 
 
    <div>4</div> 
 
    <div>5 
 
     <div>6</div> 
 
     <div> 
 
     7 
 
     <div>8</div> 
 
     <div>9</div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div> 
 
<div> 
 
<span id="carot">|</span>10 
 
</div>

因此,當插入符號爲「10」,按住左就應該到「9」但我怎麼得到這個元素?有沒有JS或jQuery功能我錯過了? jQuery最接近(),prevAll()或父母()似乎無法完成這項工作。

+0

可以使用獲得的'#caret'兄弟文本['Node.nextSibling'](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling)並減去它的編號。然後使用'$(*:contains(newNum)「)選擇元素的號碼等於新號碼。' – Mohammad

+0

當然,在文本節點上調用'css'不太可能做太多...... –

回答

0

https://jsfiddle.net/jqb816a1/5/

我想這幾個不同的解決方案。起初,我認爲DOM元素的基本向上遍歷是可行的,但不幸的是,既然你在你的問題中指定了你希望它也通過未知數目的父元素的兄弟姐妹,我無法完全理解牛仔舞。

我最終創建了一個包含Set Object的對象以保存所有這些文本節點,並且getPrev方法在給定包含頁面上的文本節點的元素時將返回以前的文本節點。在這種情況下,你span標籤與carot

的設置

function findTextNodes(node) { 
    let text_node_set = new Set(); 
    traversal(node); 

    function traversal(node) { 
    check_for_text(node); 
    let ele = node.nextSibling; 
    while (ele) { 
     check_for_text(ele); 
     ele = ele.nextSibling; 
    } 

    } 

    function check_for_text(ele) { 
    if (ele.childNodes) { 
     for (let child of ele.childNodes) { 
     if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) { 
      text_node_set.add(child); 
     } else { 
      traversal(child); 
     } 
     } 
    } 
    } 

    return { 
    getPrev: function(ele_node) { 
     let text_node; 
     if (ele_node.childNodes) { 
     for (let child of ele_node.childNodes) { 
      if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) { 
      text_node = child; 
      } 
     } 
     } 
     if (this.text_node_set.has(text_node)) { 
     let prev, previousNode; 
     this.text_node_set.forEach(function(node) { 
      if (node === text_node) { 
      if (prev) previousNode = prev; 
      } 
      prev = node; 
     }) 
     return previousNode; 
     } 
    }, 
    text_node_set 
    } 
} 

使用返回對象的ID:

let text_nodes = findTextNodes(document.body); 
// object: text_nodes 
// methods: getPrev 
// properties: text_node_set 

let caret = document.getElementById('carot'); 

//print the previous node to the console 
console.log(text_nodes.getPrev(carot)); 

//or turn its text green 
let prevNode = text_nodes.getPrev(carot); 

//(we need to grab the parent node of the text for styling) 
prevNode.parentNode.style.color = "lightGreen"; 
相關問題