使用jQuery读取URL并在li中添加类,这样我就可以使用CSS隐藏其他li了

时间:2014-02-25 11:30:32

标签: jquery jquery-ui jquery-plugins

我有URL获取页面名称并使用该页面名称我想在li上添加类,所以我可以使用CSS隐藏其他li。所有ul li列在其他页面上,并希望在页面加载时执行。例如URL:www.abc.com/jsp/templates/page_elements/uk/common/content.jsp?&page=OrderPayment-5

<ul>
        <li><a href="common/customer_service_question.jsp?page=OrderPayment-1">1</a></li>
        <li><a href="common/customer_service_question.jsp?page=OrderPayment-2">2</a></li>
        <li><a href="common/customer_service_question.jsp?page=OrderPayment-3">3</a></li>
        <li><a href="common/customer_service_question.jsp?page=OrderPayment-4">4</a></li>
        <li class="hide"><a href="common/customer_service_question.jsp?page=OrderPayment-5">5</a></li>
    </ul>

我是jQuery的新手并且混淆了如何做到这一点。

6 个答案:

答案 0 :(得分:2)

你可以用这个

<script>
$(document).ready(function () {
var link = window.location;
var pram = getURLParameter(link, 'page');
if(pram === 'OrderPayment-1')
{
 // add your class to hide first li 
 $('#listQue li').eq(0).css('display', 'none');
 or
 $('#listQue li').eq(0).addClass("hide");
}
if(pram === 'OrderPayment-2')
{
 // add your class to hide second li 
 $('#listQue li').eq(1).css('display', 'none');
 or
 $('#listQue li').eq(1).addClass("hide");
}
});
function getURLParameter(url, name) {
    return (RegExp(name + '=' + '(.+?)(&|$)').exec(url) || [, null])[1];
}
</script>

答案 1 :(得分:0)

你在找这个,

  $(document).ready(function () {
        $("li a").click(function (event) {
           $(this).parent().addClass("hide");
        });
    });

如果您需要更改类名,则应该提供锚标记属性target=_blank

<li><a href="common/customer_service_question.jsp?page=OrderPayment-1" target="_blank">1</a></li>

答案 2 :(得分:0)

您可以隐藏所有内容,并使当前处于活动状态的链接处于活动状态。并确保有一个显示器。

我认为这应该做的伎俩

var pathname = window.location.pathname;
var pathnamePart = pathname.split('/uk/');

$('ul').find('li').each(function(){
    $(this).find('a').removeClass('active');    
    if($this.find('a').attr('href') == pathnamePart[1]){
        $(this).addClass('active');
    }
});

虽未经过测试。

答案 3 :(得分:0)

我建议(虽然目前未经测试):

$('ul li a').addClass(function(){
    return this.href == window.location ? 'active' : '';
});

答案 4 :(得分:0)

使用以下选项获取网址

var pathname = $(location).attr('href'); //jquery
var pathname = window.location.pathname; //javascript

接下来使用jquery substring()

拆分字符串以获取所需内容
if(pathname.indexOf("common") >= 0){
   var url = pathname.substring(pathname.indexOf("common"))
}

现在将它与使用字符串比较的li中的值进行比较。如果你得到一个匹配你应该知道如何隐藏其他李。

答案 5 :(得分:0)

 var test=$("li").each(function(){
 var url=$(this).find('a').attr('href');
 if(url=="common/customer_service_question.jsp?page=OrderPayment-3")
 {
     //set hide css to the div.
     $(this).hide();
 }