【问题标题】:jQuery - If URL matches href then move LI to top of UL?jQuery - 如果 URL 匹配 href 然后将 LI 移动到 UL 的顶部?
【发布时间】:2011-05-07 22:07:30
【问题描述】:

一直试图让这个工作不成功。任何帮助将不胜感激。

搜索 UL,如果任何 href 等于当前 URL,则将其列表项移动到 UL 列表堆栈的顶部。

var url = window.location.toString();

$('#partnerCharities li.panel h1 a').each(function(){
   var myHref= $(this).attr('href');
   if( url.match( myHref)) {
        $(this).parent().parent().parent().before("#slider1 li:first");
   }
});

这是一个动态创建的列表(图片库),所以不确定这是否是 jQuery 不起作用的原因?这是您在 Firebug 中看到的粗略布局...

<ul id="slider">
 <li class="panel cloned"></li>
 <li class="panel">
  <article>
   <h1><a href="site.com">Example</a></h1>
  </article>
 </li>
 <li class="panel cloned"></li>
</ul>

【问题讨论】:

    标签: jquery


    【解决方案1】:

    你的代码有几个错误,看看我做的一个工作示例。

    JSFiddle

    html:

    <ul id="slider">
     <li class="panel cloned">test1</li>
     <li class="panel">
      <article>
       <h1><a href="site.com">This should come out on top.</a></h1>
      </article>
     </li>
     <li class="panel cloned">test2</li>
    </ul>
    

    js:

    var url = "site.com"; //or window.location.toString();
    
    $('#slider li.panel h1 a').each(function(){
       var myHref= $(this).attr('href');
       if( url == myHref) {
            $(this).closest("li").prependTo("#slider");
       }
    });
    

    【讨论】:

    • 太棒了!它在错误的位置添加了 LI(我认为是因为克隆的 li 总是在顶部)所以我将其更改为 .insertAfter("#slider1 li:first");它完美无缺!谢谢!
    【解决方案2】:

    即使您的问题并未真正说明这一点,我猜您希望将href 的路径部分与当前的location 匹配。

    如果是这样,并且hrefs 不会有任何查询字符串参数,您应该可以这样做:

     // get the pathname portion of the location
    var path = window.location.pathname;
    
     // get the <a> element whose href ends with the pathname, then get its <li>
    var $currentLi = $('#partnerCharities li.panel h1 a[href$=' + path + ']').closest('li');
    
     // prepend the <li> to the parent of the <li> (which is the <ul>)
    $currentLi.prependTo( $currentLi.parent() );
    

    示例: http://jsbin.com/owuye4/2/

    重点是您可能不需要遍历每个项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-27
      • 2018-04-25
      • 1970-01-01
      • 2011-04-12
      • 2021-07-28
      • 2016-04-16
      • 1970-01-01
      • 2017-11-06
      相关资源
      最近更新 更多