jQuery:根据URL添加类?id =

时间:2016-03-10 22:24:27

标签: jquery

这超出了我对jQuery的基本知识,但希望有人可以指出我正确的方向。

我需要查看网址http://something.com/pagename?id=#(#表示从1开始的数字)

获取号码,然后在a标签上找到相关的“rel”号码(或类别滑块#,如果这更容易)。

将类“on”添加到a标记中也确保删除所有其他类的“on”类(第一个标记默认为“on”类)。

<ul class="slider clearfix">

<li class="list">
<a class="change_trigger on slider1" href="javascript:void(0);" rel="1"><img     src="files/images/some1.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger slider2" href="javascript:void(0);" rel="2"><img src="files/images/some2.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger slider3" href="javascript:void(0);" rel="3"><img src="files/images/some3.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger slider4" href="javascript:void(0);" rel="4"><img src="files/images/some4.jpg" alt=""></a>
</li>
</ul>

示例:

URL

http://something.com/pagename?id=3

RESULT

<ul class="slider clearfix">

<li class="list">
<a class="change_trigger slider1" href="javascript:void(0);" rel="1"><img     src="files/images/some1.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger slider2" href="javascript:void(0);" rel="2"><img src="files/images/some2.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger on slider3" href="javascript:void(0);" rel="3"><img src="files/images/some3.jpg" alt=""></a>
</li>
<li class="list">
<a class="change_trigger slider4" href="javascript:void(0);" rel="4"><img src="files/images/some4.jpg" alt=""></a>
</li>
</ul>

由于这是非常技术性的,我已经做了一些搜索并找到了一个脚本,在查看URL字符串之后等于我不确定这是最好的方法。

function getQueryString() {
 var result = {}, queryString = location.search.substring(1),
 re = /([^&=]+)=([^&]*)/g, m;

 while (m = re.exec(queryString)) {
 result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
 }
return result;
}

window.addEventListener("load", function() {
//FIND THE RELATING REL NUMBER, ADD THE CLASS "ON", REMOVE "ON" FROM OTHERS
});

由于

2 个答案:

答案 0 :(得分:2)

将你的最后部分改为

window.addEventListener("load", function() {
//FIND THE RELATING REL NUMBER, ADD THE CLASS "ON", REMOVE "ON" FROM OTHERS
    var q = getQueryString(),
        id = q.id;

    $('.slider .change_trigger')
       .removeClass('on')
       .filter('[rel="'+id+'"]')
       .addClass('on');

});

答案 1 :(得分:0)

使用split()方法获取ID:

var urlId = url.split('?')[1].replace('id=', '');
var elem = $('.change_trigger');
elem.removeClass('on')
     .filter('[rel=' + urlId + ']')
     .addClass('on');