简体   繁体   English

单击链接两次

[英]Clicking A Link Two Times

I have a link like this : 我有这样的链接:

<a href="#" onclick="renkDegistir()" title="Yaz .......

And JS code : 和JS代码:

function renkDegistir()
    {  
        $("#cont #main article").addClass("siyah-stil");
    }

When click this link siyah-stil class is added to article. 单击此链接时,siyah-stil类将添加到文章中。 But i want to do, if link clicked 2nd time remove siyah-stil class. 但我想做,如果链接单击第二次删除siyah-stil类。

In summary , 综上所述 ,

on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");

Try using toggleClass() : 尝试使用toggleClass()

function renkDegistir()
{
    $("#cont #main article").toggleClass("siyah-stil");
}

But I'd suggest also removing the in-line onclick attribute, and switching to jQuery's click() event-handler: 但是我建议也删除onclick属性,并切换到jQuery的click()事件处理程序:

$('a').click(
    function(){
        $("#cont #main article").toggleClass("siyah-stil");
    });

Edited to address @Eray's comment (below): 编辑以解决@Eray的评论(如下):

Can you explain [to] me , why jQuery's click() function [is] better than in-line onclick attribute? 您能否向我解释一下,为什么jQuery的click()函数比内联onclick属性更好?

The reason I prefer to use non-inline code is that it reduces the complexity of changing the onClick events; 我之所以喜欢使用非内联代码,是因为它降低了更改onClick事件的复杂度。 since they get changed in one place, rather than having to change the onclick attribute in every a (or other) element. 因为他们在一个地方得到改变,而不是改变onclick属性,每a (或其他)的元素。 Admittedly, you could achieve that benefit by simply changing the renkDegistir() function, but then you end up with functions named for posterity, rather than the inherent nature of the function. 诚然,您可以通过简单地更改renkDegistir()函数获得该好处,但是最终您得到的是为后代命名的函数,而不是该函数的固有特性。

It also makes it easier for others to take over, and adapt your code, and to iron out bugs when they appear. 它还使其他人更容易接管和修改您的代码,并在出现错误时消除它们。

toggleClass does exactly that. toggleClass正是这样做的。

http://api.jquery.com/toggleClass/ http://api.jquery.com/toggleClass/

Here you go: 干得好:

JQuery - toggleClass jQuery-toggleClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM