2

I have two html button element like this.

<input type="button" class="button-a" value="Button a"/>  
<input type="button" class="button-b" value="Button b"/>

So on clicking any of the button I want to trigger the same event. So I can do that by writing some jquery code like.

<script>
  $(document).ready(function() {
    //button-a click event
    $('.button-a').click(function(){
      alert("The event triggered");
    });

    //button-b click event
    $('.button-b').click(function(){
      alert("The event triggered");
    });
 });
</script>

So can we combine both the event() together like OR condition with jQuery?

4

6 回答 6

4

试试这个代码:

<script>  
$(document).ready(function() { 
    $('.button-a, .button-b').click(function(){
          alert("The event triggered");
    });
});
</script>

http://jsfiddle.net/gNths/

于 2012-10-09T07:20:29.013 回答
1

它们是选择器,因此与 css 相同,您只需要像在 css 中那样用逗号分隔,$('.button-a,.button-b')

于 2012-10-09T07:21:25.190 回答
0
<script>  
    $(document).ready(function() { 
        $('.button-a, .button-b').click(function(){
              alert("The event triggered");
        });
    });
</script>

这个脚本对我有用。感谢大家的时间。

于 2012-10-09T07:31:27.733 回答
0

尝试$('[class^="button-"]').click( function() {...} );

于 2012-10-09T07:21:14.637 回答
0

是的。这应该这样做:

<script>  
$(document).ready(function() { 
    $('.button-a, .button-b').click(function() { 
        alert("The event triggered");    
    });
});
</script>
于 2012-10-09T07:21:32.570 回答
0
<script>
  $(document).ready(function() {
    //button-a click event
    $('.button-a').click(function(){
      ButtonClick("#button_a");
    });

    //button-b click event
    $('.button-b').click(function(){
      ButtonClick("#button_b");
    });
 });

function ButtonClick(id){
 //do something
}
</script>
于 2012-10-09T07:23:03.180 回答