开发者

Own designed toggle buttons slows down my computer after intensive use

I have a set of buttons that performs a specific action in my dynamic page. I want some of this buttons to be toggle buttons, so when I click on one of them the button turns the original image into a second image, and when clicked again, the second image turns into the first again. I've decided that the div's which will perform the function of my buttons are of class ".OptLvl3Tack". I think that I can change the image using the background css property, but due to css deals only with the pseudo events hover, visited, ..., but no click event, I think I have no other option than using Javascript. I have designed this code to do so:

function IfNoTacked(Tack){
    $(Tack).css("background", "url('{{ STATIC_URL }}ThumbTack_Click.png')");
    $(Tack).click(function(){IfTacked($(Tack))});
}
function IfTacked(Tack){
    $(Tack).css("background", "url('{{ STATIC_URL }}ThumbTack.png')");
    $(Tack).click(function(){IfNoTacked($(Tack))});
}   
$(".OptLvl3Tack").each(function(){$(this).click(func开发者_如何学编程tion(){IfNoTacked($(this));})});

The code works fine, but when I click one button, let's say, 30 times in less than 10 seconds, my computer slows down, so I have to force the web browser to be closed before my whole computer crashes. My desktop is intel i3 processor, 4gb RAM, so I think that the problem is related with the intensive use of javascript. Is it correct? or is a DOM related problem? Is there a different way to perform this operation using javascript? not using javascript?


I think you are attaching every time a new click handler. After a while your handler will be executed several times.

Try to remove the handler or remember the state of the button in a variable and decide in the click handler what to do.


most likely it's because you make use of each. Afaik you don't have to use it:

$(".OptLvl3Tack").click(function() {
IfNoTacked($(this));
});

But I would make it all 1 function:

$(".OptLvl3Tack").click(function() {
    if($(this).hasClass('active')) {
        $(this).css("background", "url('{{ STATIC_URL }}ThumbTack.png')");
        $(this).removeClass('active')
    } else {
        $(this).css("background", "url('{{ STATIC_URL }}ThumbTack_Click.png')");
        $(this).addClass('active')
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜