gpt4 book ai didi

jQueryparentsUntil() id 被发现

转载 作者:行者123 更新时间:2023-12-01 01:15:12 26 4
gpt4 key购买 nike

有没有办法制作 parentsUntil()在第一个带有 id 的元素之后停止?例如,我希望在单击 li 时返回 li ul div#id-found

<div id="id-found">
<ul>
<li></li>
</ul>
</div>

这是一个 js fiddle 示例(比这个示例稍微高级一些):http://jsfiddle.net/T9gBu/

最佳答案

这是实现您想要的目标的最佳方式:

var $t = $(this), $p = $t.parentsUntil('[id]') 
$p = $t.add($t.closest('*[id]').add($p));

现在 $p 具有向上的元素轨迹,您可以映射和连接等。

这是修改后的 fiddle http://jsfiddle.net/Exceeder/awnvowan/

你的 fiddle 也有一些问题。如果我正确理解您的需要,那么直接在映射器中处理字符串构建是最有效的:

var selector = 
$p.map(function() {
var $t = $(this),
id = $t.attr('id'),
tag = $t.prop("tagName"),
cls = $t.attr("class");
if (cls) {
cls = "." + $.trim(cls).replace(/\s/gi, ".");
} else
cls = '';

return tag + (id ? '#'+id : '') + cls;
}).get().reverse().join(" ");

更新此答案已根据 jfaron 评论进行更新。

关于jQueryparentsUntil() id 被发现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556730/

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