开发者

How do I call a jQuery live event from inside itself?

I wanting to know if anyone knows away of calling a live event inside itself with a parameter.

$('#mybutton').live('click', {param: param1), function(event) {
     alert(event.data.param);
     $('#mybutton').click('some data');
});

I had found something weird in my code which was causin开发者_如何学JAVAg the trigger event not to work.

Here is a clean version that should work.

$('#mybutton').live('click', {param: param1), function(event) {
     alert(event.data.param);
     $('#mybutton').trigger('click', ['some data']);
});


I believe trigger lets you specify additional parameters. They'll show up as extra arguments to the function rather than as items on the event.data object, but they'll get there...

Here's an example (live copy):

jQuery(function($) {

  $("#theButton").live('click', {foo: "bar"}, function(event, second) {
    display("event.data.foo = " + event.data.foo);
    display("second arg = " + second);
  });

  $("#theTrigger").click(function() {
    $("#theButton").trigger('click', "charlie");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

});

But wanting to trigger event handlers in this way usually indicates that things want a bit of refactoring. Have a function that does the work you want done, and then call that function when you want the work done — either in response to an event, or directly when you need to do the work directly (rather than triggering the event, which is indirect and not terribly clear from a maintenance perspective).

E.g.:

$('#mybutton').live('click', {param: param1), function(event) {
    doSomething(event.data.param);
});

function doSomething(param) {
    // ...do something with `param`...

    // Possibly call yourself again
    if (some_condition) {
        doSomething(some_other_param_value);
    }
}


You're close, but I think your live code is a little off:

$('#mybutton').live('click', function(event, param) {
  alert(param);
  $('#mybutton').trigger('click', ['some data']);
});

Also,

$('#mybutton').trigger('click', 'some data');

is only compatible with jQuery 1.6.2. Wrapping it in an array

$('#mybutton').trigger('click', ['some data']);

is much more backwards compatible.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜