如何使用active = true属性选择锚点,添加一个类,如果用户选择其他锚点,则将该类提供给新锚点。

时间:2018-04-18 20:15:46

标签: javascript jquery html css

我需要将一个带有Jquery的“Selected”类添加到一个锚中,捕获它的唯一方法是通过它的属性“active = true”。然后,当用户选择其他锚时,新锚将被设置为“active = true”,并且必须是新类“Selected”而另一个不是。

这个想法是必须区分选定的锚点。 “选择可能只是”。选择{color:red;}“。

        When the user selects 1
<span class="paginate_numbers">
    <a active="true" class="paginate_button paginate_number selected">1</a>
    <a class="paginate_button paginate_number">2</a>
    <a class="paginate_button paginate_number">3</a>
    <a class="paginate_button paginate_number">4</a>
    <a class="paginate_button paginate_number">5</a>
</span>

When the user selects 2
<span class="paginate_numbers">
    <a class="paginate_button paginate_number">1</a>
    <a active="true" class="paginate_button paginate_number selected">2</a>
    <a class="paginate_button paginate_number">3</a>
    <a class="paginate_button paginate_number">4</a>
    <a class="paginate_button paginate_number">5</a>
</span>

.selected {color:red;}

1 个答案:

答案 0 :(得分:0)

没有active这样的属性。并且,您似乎使用Selected类和active属性是多余的,因为一个只是表示另一个。

为什么不为 a:focus 锚点创建CSS规则?

a { text-decoration:none; }

/* When an anchor gets the focus, style it. */
a:focus {color:red; background-color:#ff0; }
<span class="paginate_numbers">
    <a href="#" class="paginate_button paginate_number">1</a>
    <a href="#" class="paginate_button paginate_number">2</a>
    <a href="#" class="paginate_button paginate_number">3</a>
    <a href="#" class="paginate_button paginate_number">4</a>
    <a href="#" class="paginate_button paginate_number">5</a>
</span>

但是,如果必须动态添加/删除类,则可以在不涉及属性的情况下执行此操作:

// Get all the appropriate links into a set
var $paginationLiks = $(".paginate_numbers a");

// Set up a click event handler for each link
$paginationLiks.on("click", function(){
  $paginationLiks.removeClass("active"); // Remove the class from all links
  $(this).addClass("active");            // Add class to clicked link
});
a { text-decoration:none; }

/* This class is applied to the clicked link */
.active {color:red; background-color:#ff0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="paginate_numbers">
    <a href="#" class="paginate_button paginate_number">1</a>
    <a href="#" class="paginate_button paginate_number">2</a>
    <a href="#" class="paginate_button paginate_number">3</a>
    <a href="#" class="paginate_button paginate_number">4</a>
    <a href="#" class="paginate_button paginate_number">5</a>
</span>