简体   繁体   中英

How to trigger the '.click' event more than once?

$('document').ready(function() {
    $('.button').click(function() {
        $('img').animate({left: "+80px"}, 2000);
    });
});

So, I'm a bit of a newbie to jQuery and stuff. All I want to do is make an image move to the right every time I click a button. When I run it, it works the first time, but when I click the button again, it just stays still.

I was wondering how I could trigger the .click event multiple times.

PS: If it's worth knowing, the button I mention here is actually a <div> . I couldn't get it to work with a <button> .

尝试+=

$('img').animate({left: "+=80px"}, 2000);

try the on event:

var doc = $(document);
doc.ready(function() {
    doc.on('click', '.button', function() {
        var imgElem = $('img');
        var imgLeft = parseInt(imgElem.css('left'));
        var distance = 80;
        var newDistance = imgLeft + distance;
        $('img').animate({left: newDistance+'px'}, 2000);
    });
});

Edit: I changed the code after "remembering" how animate works

$(document).ready(function() {
    $('.button').unbind('click').click(function() {
        $('img').animate({left: "+80px"}, 2000);
        return false;
    });
});

I must works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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