微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – jQuery循环文本出现

好吧……我放弃了!已经失去了3个小时,但无法找到解决此问题的方法

我需要能够遍历页面上给定文本的下一个出现.就像几乎每个软件上最常见的“查找”功能一样(F3 – 找到下一个).

我正在尝试使用jQuery,但无法通过任何方式使其工作.尝试:NextAll(),next(),最近()(似乎有bug),find(),eq(),children()等等,等等

Bellow是一个可以工作的示例,但它会转到页面的最后一个元素,而不是循环遍历.

function scrollMe(tow){
    var targetoffset = $("*:contains('"+tow+"'):last").offset().top;
    $('html,body').animate({scrollTop: targetoffset},1000);
}

为了清楚起见,我的页面中有一组带有文本的行(div).每次用户单击此行时,必须轻轻地向下(或向上)滚动到下一行,并显示文本(如果有).

样品:

<div onclick="scrollMe('hello');">hello</div>
<div onclick="scrollMe('world');">world</div>
<div onclick="scrollMe('foo');">foo</div>
<div onclick="scrollMe('hello');">hello</div>
<div onclick="scrollMe('bar');">bar</div>

实际上它应该被jQuery包围,但它只是为了说明.

解决方法

Here is a working example of scrolling to the next occurrence and highlighting it.

由于您将使用变量作为包含的输入,我建议跳过选择器.它速度很快,但您将无法保持变量输入的清理.

例如,这将突出显示“两个”(fiddle example)的所有文本出现:

jQuery(function($) {
   var findText = 'two';
    $('*').filter(function() {
        return $(this).children().length < 1 && $(this).text().indexOf(findText) >= 0;
    }).addClass('hilite'); 
});

要使用某种查找下一个功能的工作,您需要一个变量来跟踪当前索引,以及某种触发器:

jQuery(function($) {
   // stores the currently highlighted occurence
   var index = 0;
   var findText = 'sed';

   // you Could do this inside the click as well,here,it's cached/faster
   // inside click,it would be more dynamic and prevent memory leaks
   // just depends on your needs
   // you would also want to start with a parent element as $('*') is costly!
   var $occurrences = $('*').filter(function() {
       return $(this).children().length < 1 && $(this).text().indexOf(findText) >= 0;
    });

    // remove existing highlights,then find the next occurrence and highlight it
    $('#trigger').click(function() {
       if( index == $occurrences.length-1 ) { index = 0; }
       $occurrences.find('span.hilite').replaceWith(findText);
       var $next = $occurrences.eq(++index);
       $next.html( $next.html().replace(findText,'<span class="hilite">'+findText+'</span>') );
       $(document).scrollTop($next.offset().top-35);
       return false;
    });

    // scroll our trigger link when the screen moves so we can click it again
    $(window).scroll(function() {
        var top = $(window).scrollTop();
        $('#trigger').offset( {top: top,left: 0} );
    });

});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


jQuery表单验证提交:前台验证一(图文+视频)
jQuery表单验证提交:前台验证二(图文+视频)
jQuery如何实时监听获取input输入框的值
JQuery怎么判断元素是否存在
jQuery如何实现定时重定向
jquery如何获取复选框选中的值
jQuery如何清空form表单数据
jQuery怎么删除元素节点
JQuery怎么循环输出数组元素
jquery怎么实现点击刷新当前页面