2011-11-10 94 views
-1

我有一張表在記錄器中用PHP鑽出。我正在使用該表來更新定價。我有一個文本輸入和一個表單按鈕。該按鈕觸發Ajax調用並更新表格。現在我有重複區域內的jQuery腳本,但有時我有超過500條記錄..現在我使用btn_2345,其中2345是唯一的我會和腳本點擊btn_2345。我如何才能在重複之外使用腳本一次,並獲取輸入文本框和唯一ID的值。使用jquery從文本框中獲取文本值

回答

3

如果你有一個這樣的表:

<table> 
    <tr> 
     <td><input type="text"></td> 
     <td><button>go</button></td> 
    </tr> 
    <tr> 
     <td><input type="text"></td> 
     <td><button>go</button></td> 
    </tr> 
    <!-- ... --> 
</table> 

然後,你可以一個data-id屬性添加到行,從<button><tr>走了DOM來獲取ID,然後倒回去了DOM找到<input>。該HTML會有點像這樣:

<table> 
    <tr data-id="11"> 
     <td><input type="text"></td> 
     <td><button>go</button></td> 
    </tr> 
    <tr data-id="23"> 
     <td><input type="text"></td> 
     <td><button>go</button></td> 
    </tr> 
    <!-- ... --> 
</table> 

和JavaScript排序是這樣的:

$('table button').click(function() { 
    var $tr = $(this).closest('tr'); 
    var id = $tr.data('id'); 
    var val = $tr.find('input[type=text]').val(); 
    // ... 
}); 

你也可以把click處理程序在一個名爲功能,如果你喜歡。

你可以讓它更漂亮的一類連接到<tr>元素和使用類closest:如果你產生了很多行,其中每HTML

<table> 
    <tr data-id="11" class="one-chunk"> 
     <td><input type="text"></td> 
     <!--...--> 

$('table button').click(function() { 
    var $chunk = $(this).closest('one-chunk'); 
    var id  = $chunk.data('id'); 
    var val = $chunk.find('input[type=text]').val(); 
    //... 
}); 
+0

有趣的使用HTML5數據屬性。 –

+0

@Yzmir:我使用這種風格很多,它使得每個塊模板更加簡單,而jQuery只是鬆散地綁定到HTML結構。給''添加一個類並使用'$(this).closest('。some-class')'會更好。 –

+0

非常感謝。看起來正是我需要的。如果我需要傳遞一對隱藏的變量,我該怎麼做。我看到你正在使用$ re –

0

爲什麼不使用

<input type="submit" class="my-button" id="2345"> 

那麼您可以在jQuery的使用類作爲選擇器,並使用id作爲你所需要的價值。

0

行有一個與之關聯的按鈕,爲什麼不只是生成onClickrowId,每次迭代都可用:

onClick="javascript: edit(rowId);" 

所以生成的結果看起來是這樣的:

<table> 
    <tr> 
     <td><input type="text"></td> 
     <td><button onclick="javascript: edit('2345');">edit</button></td> 
    </tr> 
    <tr> 
     <td><input type="text"></td> 
     <td><button onclick="javascript: edit('2346');">edit</button></td> 
    </tr> 
    .... 
</table> 

如果你不需要猜測ID。