2011-10-26 28 views
2

我有一個表,其中包含幾行,每行包含一個按鈕和一個文本框。處理表內部的jQuery點擊事件

用文本框的值觸發警報的最簡單方法是什麼?

+0

textbox? textarea是什麼意思?警惕什麼行動? –

回答

7

可以綁定一個單擊處理程序遍歷了DOM其含有<tr>,然後按鈕從那裏找到的文本框:

// Bind a click handler to all buttons in the table... 
$('table :button').click(function() { 

    var text = $(this) // "this" is the button which was clicked 
    .closest('tr')  // find the <tr> which contains it... 
    .find(':text')  // find the text box within that <tr>... 
    .val();    // and get its value 

    alert(text); 
}); 
3

如果文本輸入和按鈕是僅有的兩個在一排(<tr>),那麼你可以使用一個事件處理程序是這樣的:

$('#table_id').delegate('a', function() { 
    alert($(this).closest('tr').find('input[type="text"]').val()); 
}); 

如果按鈕是一個表單元素,你可以用'input[type="button"]'更換'a'選擇。