开发者

jQuery faking click event

Lets say I have code:

$('#target').click(function() {
  alert('Handler for .click() called.');
});

I want that after page is loaded #target would be auto clicked, yet click function remain active.

For example same button for play and stop. This开发者_JAVA技巧 would launch play method but if pressed again would stop that.

Should I just trow it to separate method or if there is single line call for such event?


It's quite simple and you almost had it...

$('#target').click(function() {
  alert('Handler for .click() called.');
}).click();

Here's a fiddle: http://jsfiddle.net/gislikonrad/xqKBE/


// when the page is ready
$(function() {
    $('#target').click(function() {
        alert('Handler for .click() called.');
    });

    // trigger click handler for #target
    $("#target").trigger('click');
});


$('#target').trigger("click");


I think you should the use toggle() event (not to be confused with toggle for showing and hiding!) as this handles multiple functions off the same event. You can then call click() after binding to call it once automatically:

$('#target').toggle(function() {
  $(this).text('Stop');
}, function() {
  $(this).text('Play');
}).click();

JSFiddle Example

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜