当使用jquery单击锚标记链接时,如何更改元素的类

时间:2013-09-20 12:25:05

标签: jquery html css class anchor

那么,如何更改具有锚标记链接使用jquery激活的ID的元素的类(active / non_active)?

HTML:

<a href="#element1">Show element 1</a>
<a href="#element2">Show element 2</a>

<div id="element1" class="active"><p>Element 1</p></div>
<div id="element2" class="non_active"><p>Element 2</p></div>

CSS:

.active{ visibility:visible; }
.non_active{ visibility:hidden; }

提前致谢!

5 个答案:

答案 0 :(得分:4)

尝试

<a class="accordion-header" href="#element1">Show element 1</a>
<a class="accordion-header" href="#element2">Show element 2</a>
<div id="element1" class="element active">
    <p>Element 1</p>
</div>
<div id="element2" class="element">
    <p>Element 2</p>
</div>

然后

var $els = $('.element');
$els.not('.active').hide()
$(".accordion-header").on("click", function (e) {
    var $target = $($(this).attr('href')).show()
    $els.not($target).hide()
    e.preventDefault();
});

演示:Fiddle

答案 1 :(得分:2)

您可以从点击的元素中取出href并将其用作选择器:

$("a").on("click", function() {
  $("div.active").toggleClass("active non-active");
  $($(this).attr("href")).toggleClass("active non-active");
});

答案 2 :(得分:0)

$("a").click(function(){
   $(a).removeClass("active");// Nake all the existing links inactive by removing class active
   $(this).addClass("active"); //then make current link as active
});

答案 3 :(得分:0)

non_active课程是否必要?我会省略它,然后使用jQuery我将执行以下操作(为了可读性而扩展了一点):

$('a').on('click', function(e){
    e.preventDefault(); // prevent the default <a> behaviour

    var $elm = $(this), // store the clicked element
        activateElement = $elm.attr('href'); // get the value of the href attribute

    $('.active').removeClass('active'); // remove currently active element

    $(activateElement).addClass('active');  // set clicked element to active by removing non_active
});

<强> CSS:

div{ visibility: hidden; }
.active{ visibility:visible; }

<强> Demo

答案 4 :(得分:0)

$("a").on("click", function() {
  var id = $(this).attr('href');
  $('.active').removeClass('active'); // remove existing active
  $(id).addClass('active'); // set current link as active
//or
//$(id).attr('class','active'); // set current link as active

});