4

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

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

提前致谢!

4

5 回答 5

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

演示:小提琴

于 2013-09-20T12:28:15.087 回答
2

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

$("a").on("click", function() {
  $("div.active").toggleClass("active non-active");
  $($(this).attr("href")).toggleClass("active non-active");
});
于 2013-09-20T12:26:46.643 回答
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

});
于 2013-09-20T12:39:15.043 回答
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; }

演示

于 2013-09-20T12:33:53.503 回答
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
});
于 2013-09-20T12:32:33.097 回答