开发者

Call the same handler with different selectors which return the same HTML object

Is an event handler bound to an element, so you can trigger the event with different selectors? Look the example below to see what I want to know:

Example:

HTML

<ul id="itemsList">
<li class="items" id="item1">element1</li>
<li class="items" id="item2">element2</li>
<li class="items" id="item3">element3</li>
</ul>

Javascript in which click event handler is defined:

$('.it开发者_如何学Goems').click(function(){
    //do something
});

To invoque this handler I think it's possible to do in several ways, using different selectors, therefore $('#item1').click(); and $(#itemsList li).eq(1).click(); would call the same event handler. Right?

If yes I'm certainly doing something wrong because it's not working properly...


I have a few things to point out:

  • Don't forget " in the expression $(#itemsList li).eq(1).click();
  • .eq(1) actually selects second li, because eq index starts at 0.

Correct syntax:

// define handler
$('.items').click(function(){
    alert($(this).text() + " clicked");
});

// call handler
$('#item1').click() ;

$("#itemsList li").eq(0).click();

jsFiddle demo


What you already do invokes this handler: http://jsfiddle.net/a3tNM/

$('#item1').click(); and $(#itemsList li).eq(1).click(); Would not call the same handler. It creates a new one.


Calling .click() with no arguments or .trigger('click') should call the click event handler on the results of your selector. As pinouchon has pointed out be careful with your selector syntax, using quotes where appropriate and remembering that .eq() is zero-indexed meaning that .eq(1) will select the second li element.

Ultimately, to call the event handler I think what you want is:

$('#itemsList li').eq(0).click();

Or indeed,

$('#item1').click();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜