gpt4 book ai didi

jquery - 使用 JQuery 定位 div 内展开的文本

转载 作者:行者123 更新时间:2023-12-01 02:13:47 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来仅包装元素的内部文本,我不想定位任何其他内部 dom 元素。例如。

<ul>
<li class="this-one">
this is my item
<ul>
<li>
this is a sub element
</li>
</ul>
</li>
</ul>

我想使用 jQuery 来做到这一点。

<ul>
<li class="this-one">
<div class="tree-item-text">this is my item</div>
<ul>
<li>
<div class="tree-item-text">this is a sub element</div>
</li>
</ul>
</li>
</ul>

一点背景是我需要制作一个内部树结构 ui 元素,所以我使用 UL 结构来表示它。但我不希望开发人员必须执行任何特殊格式才能使用该小部件。

更新:我只是想添加此操作的目的是我想添加一个单击监听器以便能够展开 li 下的元素,但是,由于这些元素位于 li 内,即使单击时单击监听器也会激活对于 children ,所以我想将它附加到文本上,为此,文本需要是可定位的,这就是为什么我想将它包装在它自己的 div 中。

到目前为止,我已经想出将 li 的所有内部元素包装在 div 中,然后将所有内部 dom 元素移回原始父级。但对于可能更简单并且不需要太多 DOM 操作的东西来说,这段代码相当繁重。

编辑:想分享我想出的第一个伪替代方案,但我认为这对于我想要完成的任务来说非常艰巨。

var innerTextThing = $("ul.tree ul").parents("li").wrapInner("<div class='tree-node-text'>");

$(innerTextThing.find(".tree-node-text")).each(function(){
$(this).after($(this).children("ul"));
});

回答:我最终做了以下操作,仅供引用,我只需要担心 FF 和 IE 兼容性,因此它在其他浏览器中未经测试。

    //this will wrap all li textNodes in a div so we can target them.
$(that).find("li").contents()
.filter(function () {
return this.nodeType == 3;
}).each(function () {
if (
//these are for IE and FF compatibility
(this.textContent != undefined && this.textContent.trim() != "")
||
(this.innerText != undefined && this.innerText.trim() != "")
) {
$(this).wrap("<div class='tree-node-text'>");
}
});

最佳答案

使用wrapInner():

​$('li').wrapInner('<div class="tree-item-text" />');​

JS Fiddle demo .

<小时/>

编辑以解决OP在下面的评论中提出的问题:

wrap inner will wrap all the elements inside the li with the div, i just want to target the text.

此修改后的代码应仅包含 textNodes:

$('li').each(
function(){
var kids = this.childNodes;
for (var i=0,len=kids.length;i<len;i++){
if (kids[i].nodeName == '#text'){
$(kids[i]).wrap('<div class="tree-item-text" />');
}
}
});​

JS Fiddle demo .

引用文献:

关于jquery - 使用 JQuery 定位 div 内展开的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9745149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com