jQuery – 如果URL匹配href,那么将LI移到UL的顶部?
一直试图让这个工作失败。 任何帮助,将不胜感激。
搜索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中看到的粗略布局……
你的代码有几个错误,看看我做的一个工作示例。
的jsfiddle
HTML:
- test1
-
This should come out on top.
- test2
JS:
var url = "https://stackoverflow.com/questions/4145420/jquery-if-url-matches-href-then-move-li-to-top-of-ul/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"); } });
即使你的问题没有真正说明这一点,我猜你想要匹配href
的路径部分到当前location
。
如果是这样,并且hrefs
将没有任何查询字符串参数,您应该能够执行以下操作:
// get the pathname portion of the location var path = window.location.pathname; // get the element whose href ends with the pathname, then get its var $currentLi = $('#partnerCharities li.panel h1 a[href$=' + path + ']').closest('li'); // prepend the to the parent of the (which is the ) $currentLi.prependTo( $currentLi.parent() );
示例: http : //jsbin.com/owuye4/2/
重点是您可能不需要迭代每个项目。