开发者

How do I trigger a single event defined for a class of objects

I have a question. I have 8 buttons that have unique incrementing id's and a shared class.

<button class="btnChapter" id="btnChapter_1" value="1">1</button>
<button class="btnChapter" id="btnChapter_2" value="2">2</button>
<button class="btnChapter" id="btnChapter_3" value="3">3</button>
...

开发者_JS百科In order to prevent me from duplicating code, I bound a click event to the btnChapter class instead of binding an event individually to each button's ID.

$('.btnChapter').click(function(){ .. do stuff .. });

How do I trigger() the click() event only for #btnChapter_2? The following doesn't seem to work.

$('#btnChapter_2').click()


Your code is perfectly fine.

The only thing that you could possibly be doing wrong in my opinion is not executing this code after the ready event.

I'd also suggest the use of live.

Try this:

$(function() {
  $('.btnChapter').live('click', function(){ 
      //blah
  });
  //...
  $('#btnChapter_2').click();
});


Your code seems to be fine. Can you check whether the click event is actually binded to the button controls.

One reason I can think of is the code is the javascript is executed before the dom is ready, so the $('.btnChapter') selector may not return any element.

Can you check what is the value returned by $('.btnChapter').length soon after the click event is binded.

Note: Can you manually click on the buttons and check whether the event is fired?

Here is a sample I did in JSFIDDLE, it works fine for me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜