![](/img/trans.png)
[英]How to wrap text nodes with mixed <a> tags with jQuery?
[英]Javascript wrap all text nodes in tags
我知道有人問過這個問題,但幾乎所有答案都使用jQuery的wrap
函數。 我試圖找出一種簡單的javascript方式:
<div id="content">
"hey"
<br>
<br>
"foo"
"bar"
</div>
<script>
function mainFocusOut(e) {
//here or any other focus outs...create a function to look between <br> tags and put everything into divs
if (e == 'undefined') e = window.event;
var target = e.target || e.srcElement;
for (var i = 0; i < target.childNodes.length; i++) {
//I'm not sure if I need a closure function here inside the loop so it works on each individual textNode
(function(i) {
var curNode = target.childNodes[i];
if (curNode.nodeName === "#text") {
var element = document.createElement("div");
element.appendChild(curNode);
target.insertBefore(element, curNode);
//NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
}
})(i);
}
}
</script>
當然,所需的輸出是所有位於div標簽之間,相同位置的文本節點。 我究竟做錯了什么? 是否像我在這里一樣簡單,只是一個簡單的循環?
在我看來,您要做的就是在這兩行之間切換:
element.appendChild(curNode);
target.insertBefore(element, curNode);
變成:
target.insertBefore(element, curNode);
element.appendChild(curNode);
因為現在,在將div放置在正確的位置之前,請將curNode附加到新的div。 結果是:
<div>"hey"</div>
太好了,但是為了將div放在正確的位置,您不能再將它放在"hey"
之前,因為您只是將其放在div內。
通過交換兩行,您首先將div放在"hey"
前面:
<div></div>"hey"
然后在div內正確定位“嘿”:
<div>"hey"</div>
我希望這有幫助!
以下是一個取決於字符串對象方法split
和indexOf
的解決方案
<script>
function enclose(id, cutString){
out = '';
target = document.getElementById(id);
text = target.innerHTML;
if (text.indexOf(cutString) == -1){
return true;
}
parts = text.split(cutString);
for (i = 0; i < parts.length; i++){
out += '<div class="new-div">'+parts[i]+'</div>';
}
target.innerHTML = out;
}
</script>
簽出此演示
下面的演示是對通過for
循環使用match(/\\w/gi)
條件檢查來忽略空零件的更新。 在這里結帳。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.