开发者

Bind jQuery click event only to certain buttons

I have a website which create various inputs dynamically.

I have 3 specific inputs which I would like to call a JQuery function when clicked.

<input type="button" name="Finish" value="Finish">
<input type="button" name="Update" value="Update">
<input type="button" name="Cancel" value="Cancel"> 

Was using this code:

jQuery(":button").click(function(){
    //Do summat
}):

but this was making all the inputs on the page call the function when I only want the 3 inputs above to call the function. Is this possi开发者_运维知识库ble?

uggers


Give them a class name and use this one in the selector. E.g. class="clickyButton" and $('.clickyButton').click(function() { /* your code *) });


On a side-note, there is no need to write jQuery instead of $. If you don't want $ in the global namespace for some reason (and thus called $.noConflict();), you can still wrap your code in a function containing $ mapped to jQuery:

(function($) {
    /* your code using $ here */
})(jQuery);


Use a parent element to scope your buttons properly

HTML

<div id="my-group">
    <input type="button" name="Finish" value="Finish">
    <input type="button" name="Update" value="Update">
    <input type="button" name="Cancel" value="Cancel">
</div>

<div id="not-my-group">
    <input type="button" name="Finish" value="Finish">
    <input type="button" name="Update" value="Update">
    <input type="button" name="Cancel" value="Cancel">
</div>

JS

$("#my-group :button").click(function(){
    alert('foobar');
});

http://jsfiddle.net/wpELC/2/

Using the parent selector #my-group will let you target only specific button groups.


Use class to identify what action you want to take.

<input class="Finish" type="button" name="Finish" value="Finish">
<input class="Update" type="button" name="Update" value="Update">
<input class="Cancel" type="button" name="Cancel" value="Cancel"> 

Then use the following:

$('.Finish').click(function() { /* Finish code */ });
$('.Update').click(function() { /* Update code */ });
$('.Cancel').click(function() { /* Cancel code */ });


You need to be more "selective":

<input class="buttongroup" type="button" name="Finish" value="Finish">
<input class="buttongroup" type="button" name="Update" value="Update">
<input class="buttongroup" type="button" name="Cancel" value="Cancel"> 

Then:

jQuery("input.buttongroup").click (function(){
    //Do stuff
}):


If the name attributes you have are unique, you can just use those:

$("input").filter(function() {
  return this.name.match(/Finish|Update|Cancel/);
}).click(function() { 
  // example of doing something
  alert($(this).val()); 
});

If they are not unique, you will have to add something unique to them like a class or id, as shown in other answers

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜