jQuery - 如果URL匹配href,那么将LI移到UL的顶部?

时间:2010-11-10 14:18:43

标签: jquery

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

搜索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>

2 个答案:

答案 0 :(得分:3)

您的代码存在多处错误,请查看我制作的实例。

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");
   }
});

答案 1 :(得分:0)

即使你的问题没有说明这一点,我猜你想要匹配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/

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