2011-01-29 91 views
2

我有一個網站可以動態創建各種輸入。將jQuery點擊事件綁定到某些按鈕

我有3個特定的輸入,我想單擊時調用JQuery函數。

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

使用此代碼:

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

但這是使所有的頁面上輸入調用函數時,我只希望上面的3個輸入調用的函數。這可能嗎?

uggers

回答

7

給他們一個類名並在選擇器中使用它。例如。 class="clickyButton"$('.clickyButton').click(function() { /* your code *) });


在一個側面說明,沒有必要寫jQuery,而不是$。如果你不想在全局命名空間$出於某種原因(因此稱爲$.noConflict();),你仍然可以在包含$映射到jQuery的函數代碼:

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

你需要更多的「選擇性「:

<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"> 

然後:

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

jQuery(),而不是jquery() - 而不是[類型=按鈕]使用jQuery的:按鈕選擇器會更好(但你根本不需要 - 簡單'.buttongroup'就足夠了) – ThiefMaster 2011-01-30 00:01:58

4

使用父元素範圍的按鈕正確

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/

使用家長選擇#my-group會讓你只針對特定的按鈕組。

0

如果name屬性你是獨一無二的,你可以使用這些:

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

如果不是唯一的,你將有獨特的東西添加到他們像一類或ID,如圖其他答案