-1
<div class="myclass selected">
    <h2 class = "title">#Content 1</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 2</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 3</h2>
</div>
<div class="myclass">
    <h2 class = "title">#Content 4</h2>
</div>

我想在 url 中显示为“http://example.com/#content-1”,并希望为每个选择进行更新。使用 jquery 可以做到这一点吗?

4

2 回答 2

2
$('.myclass h2').click(function(){
    window.location = 'http://example.com/' + $.text(this).toLowerCase().replace(/ /g, '-');
});

您是否有任何理由不使用常规链接?尝试这个:

<div class="myclass selected">
    <h2 class="title">
        <a href="#content-1">#Content 1</a>
    </h2>
</div>
<!-- Add the others here... -->

然后,只需添加此脚本:

jQuery(function() {
    var hash = window.location.hash;
    hash && $('.myclass').removeClass('selected').filter(function(){
        return $(this).find('a').prop('href') == hash;
    }).addClass('selected');
});
于 2012-08-24T01:22:07.620 回答
0

改变这个

 var selected = $('.selected');
    selected.removeClass('selected');
    selected.hide();

    var next = selected.next(".myclass");

 var selected = $('.selected');
 var next = selected.next(".myclass");
 selected.removeClass('selected');
 selected.hide();

selected在将其分配给next..之前,您正在删除该类

http://jsfiddle.net/wirey00/Jqfsn/1/

于 2012-08-24T02:54:08.177 回答