开发者

Clicking A Link Two Times

开发者 https://www.devze.com 2023-02-05 20:36 出处:网络
I have a link like this : <a href=\"#\" onclick=\"renkDegistir()\" title=\"Yaz ....... And JS code :

I have a link like this :

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

And JS code :

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

When click this link siyah-stil class is added to article. But i want to do, if li开发者_开发问答nk clicked 2nd time remove siyah-stil class.

In summary ,

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


Try using 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:

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

Edited to address @Eray's comment (below):

Can you explain [to] me , why jQuery's click() function [is] better than in-line onclick attribute?

The reason I prefer to use non-inline code is that it reduces the complexity of changing the onClick events; since they get changed in one place, rather than having to change the onclick attribute in every a (or other) element. 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.

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.

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


Here you go:

JQuery - toggleClass

0

精彩评论

暂无评论...
验证码 换一张
取 消