如何从当前插入符号移动到具有特定类名的标记

How to move to the tag with has specific class name from a current caret

本文关键字:插入 移动 符号      更新时间:2023-09-26

我正在编写搜索HTML的程序。

我用 span 标签包装了搜索关键字,该标签事先具有"查找"类,如下所示:

<b><span class="find">A</span>
    <i>B</i>C</b>DDD<b><span class="find">A</span></span><i>B</i>C</b>
当单击"下一个"

或"上一个"按钮时,我想从当前选择点移动到最近的下一个/上一个跨度标签(我从window.getSelection()那里得到)。

如果"jQuery(selection.focusNode).next('.find');"可以用于它,我会简单地解决它,但它是无效的。有什么好方法吗?

也许你可以做这样的事情:

var foo = {
    spans: $('span.find'),
    pos: -1,
    getSpan: function(inc) {
        var pos = this.pos + inc;
        if (pos >= 0 && pos < this.spans.length) {
            this.pos = pos;
            return this.spans[this.pos];
        }
        return undefined;
    },
    next: function() {
        var span = this.getSpan(1);
        // do what you have to do with it
    },
    prev: function() {
        var span = this.getSpan(-1);
        // do what you have to do with it
    },
}

然后"连接"下一个返回您的按钮。

这就是你要找的?

http://jsfiddle.net/sLwuN/

爪哇语

$("#prev").click(function(){
    foundElement($(getSelection().focusNode.parentNode).prevAll('.find').first());
});
$("#next").click(function(){
    foundElement($(getSelection().focusNode.parentNode).nextAll('.find').first());
});
function foundElement ($element) {
    if ($element) {
        $element.css('color', 'red');
        setTimeout(function () {
            $element.css('color', 'inherit');
        }, 500);
    }
}

.HTML

<span class="find">A</span>
<i>BBBBB</i>
<span class="find">B</span>
<span class="find">CC</span>
<i>CCCCCC</i>
<span class="find">D</span>
<button id="prev">prev</button>
<button id="next">next</button>