在我的HTML文档中,我得到了一个带有空表体的表,当文档完全加载时,jQuery会自动填充该表。表体由PHP脚本生成,jQuery通过简单的GET请求获取内容。
这是我的PHP代码..。
<?php
// ...
// ...
// Just take a look at the following two lines,
// the other code is not important in this case.
while ($tableDataRow = $tableData->fetch_assoc())
echo '<tr><td>'. $tableDataRow['id']. '</td><td>'. $tableDataRow['name']. '</td><td><a href="#" class="delete-row" data-id="'. $tableDataRow['id']. '">Delete</a></td></tr>';
?>输出可能是..。
<tr><td>1</td><td>Nadine</td><td><a href="#" class="delete-row" data-id="1">Delete</a></td></tr><tr><td>2</td><td>Nicole</td><td><a href="#" class="delete-row" data-id="2">Delete</a></td></tr>一切都很完美,唯一的问题是,如果发生任何单击事件,jQuery都不会做出反应。我的jQuery代码是这样的..。
$(document).ready(function() {
$(".delete-row").click(function(event) { // "a[class=delete-row]" does not work, too. But "*" works for every element, even for the links?!
event.preventDefault();
alert("You clicked on that link!")
});
});发布于 2013-07-31 12:53:07
.click()使用jQuery的bind()方法,它基本上是对DOM的快照。在这种情况下,将在文档就绪时生成该快照。
由于PHP代码是动态添加到页面中的,这将不包含在document快照中。出于这个原因,jQuery有一个on()方法,可以用它来代替:
$("table").on('click', '.delete-row', function() { ... });这就是所谓的事件委派。
发布于 2013-07-31 12:52:31
使用委托:
$(document).ready(function() {
$("#mytable").on("click",".delete-row",function(event) { // "a[class=delete-row]" does not work, too. But "*" works for every element, even for the links?!
event.preventDefault();
alert("You clicked on that link!")
});
});发布于 2013-07-31 12:52:46
事件在生成页面时是绑定的,但是您的表是在后面附加的,因此您应该使用类似于"on“之类的内容,或者使用最新的jQuery事件绑定方法,而不是”单击“。
https://stackoverflow.com/questions/17970897
复制相似问题