[英]jquery click() doesn't work
我對jQuery click()函數有問題。
我使用此函數以編程方式單擊一個鏈接,該鏈接調用一個ajax函數,該函數將一個新對象添加到數據庫中。
當我提交表單時,在帶有新鏈接的新對象的對象數據表中添加了tr,我想以編程方式單擊此新鏈接以加載並顯示對象屬性。
問題是DOM中不存在帶有td和link的新tr,並且功能$.('#elem').click')
不起作用。
我在其他帖子中看到,我必須將click事件與新的.on函數綁定在一起,如下所示:
$('#parent-items').on('click', 'elem', function() {
// [...]
});
我不知道要寫些什么來代替[...],在我的JavaScript代碼末尾,我這樣調用click函數:
$('#myelem').click();
謝謝你的幫助
實際上並不難。 :)
<table id="list">
<tr>
<td>John</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
<tr>
<td>Lucy</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
<tr>
<td>Sam</td>
<td><a class="btn-hi">Say Hi!</a></td>
<td><a class="btn-bye">Say Goodbye!</a></td>
</tr>
</table>
<script>
$('#list').on('click', 'a', function() {
// Wrap the clicked <a> element with jQuery
var $this = $(this);
// Get the parent <tr> element
var $tr = $this.closest('tr');
// Get all (direct) children elements (<td>) that are inside the current <tr> element
var $tds = $tr.children();
// Get the text from the first <td> element in the current row
var name = $tds.eq(0).text();
// Get the type (class name) of clicked link
var type = $this.attr('class');
if (type == 'btn-hi') {
alert( 'Hi, ' + name + '!' );
} else if (type == 'btn-bye') {
alert( 'Goodbye, ' + name + '!' );
}
});
</script>
在JSBin中查看此演示: http : //jsbin.com/welcome/38776/edit
每當用戶單擊<table id="list">
元素內的任何<a>
元素時,click事件都將執行。 稱為“事件委托” -http://api.jquery.com/delegate/
因此,您可以向表中動態添加更多行,並且一切仍將正常進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.