jQuery - 前一个节点 - 没有公共父节点

发布于 2024-09-11 03:46:16 字数 1005 浏览 2 评论 0原文

使用 jQuery 我想从给定节点找到前一个节点。前面的节点和给定的节点可能没有相同的父节点!请检查以下片段:

<div class="container">
<div id="sec1">
    <p>Some text</p>
    <p><b>Some</b> text<</p>
    <p>Some <b>more</b> text</p>
</div>
<div id="sec2">
    <p>just a text</p>
</div>
<div id="sec3">
    <p>another <span id="cursorPos1"></span>text</p>
    <p><b>yet</b> another<span id="cursorPos2"></span> text</p>
</div>

假设当前给定节点是 $("span#cursorPos1"),并且我想要定位的是前面的粗体文本,那么结果应该是 "more< ;/b>”。这里,给定节点位于 div#sec3 中,目标前一个节点位于 div#sec1 中。

如果当前给定节点为 $("span#cursorPos2"),则前面的粗体文本为“yet”。这里,给定节点和目标前一个节点都在同一个 div#sec3 中。

基本上,根本不应该考虑层次结构。从给定的节点,选择器应该简单地找到前面的匹配项。

请告诉我如何做到这一点。

谢谢
斯里坎特

Using jQuery I would like to locate a preceding node from a given node. The preceding node and the given node may not have the same parent node! Please check the following fragment:

<div class="container">
<div id="sec1">
    <p>Some text</p>
    <p><b>Some</b> text<</p>
    <p>Some <b>more</b> text</p>
</div>
<div id="sec2">
    <p>just a text</p>
</div>
<div id="sec3">
    <p>another <span id="cursorPos1"></span>text</p>
    <p><b>yet</b> another<span id="cursorPos2"></span> text</p>
</div>

Supposing if the current given node is $("span#cursorPos1"), and what I would like to locate is the preceding bold text, then the result should be "<b>more</b>". Here, the given node is in div#sec3, and the target preceding node is in div#sec1.

If the current given node is $("span#cursorPos2"), then the preceding bold text is "<b>yet</b>". Here, both the given node and the target preceding node are in the same div#sec3.

Basically, the hierarchy should not be considered at all. From a given node the selector should simply find the preceding match.

Please let me know on how this can be done.

Thanks
Srikanth

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

氛圍 2024-09-18 03:46:16

这不是一个很好的解决方案,但我认为这可以解决问题。想法是找到所有粗体标签和光标元素,在结果数组中查找光标的位置,然后返回其之前的元素。

只是把这些放在一起,可能还有更好的方法。如果你使用它,一些错误检查可能也是合适的。

prevBold = function(myId) {

var boldAndMe = $('#' + myId + ', b').toArray();
    var me = $('#' + myId).get(0);
    var myPos = boldAndMe.indexOf( me );

    return myPos > 0 ? $( boldAndMe[myPos-1] ) : null;

}

Not a very nice solution, but i think this does the trick. Idea is to find all bold tags and the cursor element, look for position of the cursor in the resulting array, and then return the element before it.

just threw this together, there are probably better ways. if you use this, some error checking is probably in order too.

prevBold = function(myId) {

var boldAndMe = $('#' + myId + ', b').toArray();
    var me = $('#' + myId).get(0);
    var myPos = boldAndMe.indexOf( me );

    return myPos > 0 ? $( boldAndMe[myPos-1] ) : null;

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文