1

有什么办法可以将Class添加到多个链接?我有两个不同的 div 包含相同的链接集;单击链接应将相同的类应用于另一个 div 集中的“等效”链接。

<style>
.one{margin:70px 0}
.one a{ margin:10px; padding:5px 10px; background-color:green; text-decoration: none; color:white}
.selected{background-color: yellow;}
</style>
<div class="one">
<a href="#first">1</a><a href="#second">2</a><a href="#third">3</a>
</div>

<div class="two">
<a href="#first">1</a><a href="#second">2</a><a href="#third">3</a>
</div>
<script>
$("a.one").click(function() {
    $(this).addClass(".selected").filter(':first').click();
});
</script>
4

3 回答 3

0

I would try to introduce something in common with all the links that must change together. In this I introduced a class to identify them:

<style>
.one{margin:70px 0}
.one a{ margin:10px; padding:5px 10px; background-color:green; text-decoration: none; color:white}
.selected{background-color: yellow;}
</style>
<div class="one">
<a href="#first" class="1">1</a><a href="#second" class="2">2</a><a href="#third" class="3">3</a>
</div>

<div class="two">
<a href="#first" class="1">1</a><a href="#second" class="2">2</a><a href="#third" class="3">3</a>
</div>
<script>
    $(document).ready(function() {
        $("a.1").click(function() {
            $("a.1").addClass("selected");
            $("a:not(.1)").removeClass("selected");
        });
        $("a.2").click(function () {
            $("a.2").addClass("selected");
            $("a:not(.2)").removeClass("selected");
        });
       $("a.3").click(function () {
            $("a.3").addClass("selected");
            $("a:not(.3)").removeClass("selected");
        });
    });
    </script>

Note: if the browser you are targetting does not support css3 you can't rely on :not selector and I should use some "old style" methods to remove the class.

于 2013-03-22T05:01:55.567 回答
0

此代码将帮助您...

$("a").addClass(".selected");
于 2013-03-22T04:34:51.427 回答
0

关联

首先,您需要找到锚的索引。然后根据该索引在第二个 div 锚中应用类。

$('.two').children('a').eq($('.one a').index(this)).addClass('selected');

 $('.one').children('a').eq($('.two a').index(this)).addClass('selected');
于 2013-03-22T04:38:22.623 回答