我有以下HTML结构:
<table class="table table-hover js-integrations js-radio-rows">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Owner</th>
<th>Modified Date</th>
</tr>
</thead>
<tbody>
<!-- Start load by ajax -->
<tr class="clickable">
<td class="js-integration-option">
<input type="radio" value="20" name="integration_id" class="pseudo-radio sr-only">
<label class="icon-lg" for="http-radio"></label>
</td>
<td>
<img align="absmiddle" src="imglocation" />
Some Title
<span class="file-size">
(50kb)
</span>
</td>
<td>
Owner Le Own
</td>
<td>
Date
</td>
</tr>
<!-- End load by ajax -->
</tbody>
</table>
我有这个jQuery
jQuery(document).ready(function(){
console.log('here1');
jQuery('.js-radio-rows').on('click', 'tr', function() {
console.log('here2');
});
});
当我点击可点击的行,console.log('here2')
不触发。知道我哪里做错了吗?可能是因为行是通过ajax加载的吗?这发生在document ready被调用很久之后,因为它依赖于被点击的其他东西。
如果.js-radio-rows
表在文档上不可用。准备事件,这将不起作用。尝试将document
设置为事件的委托:
jQuery(document).on('click', '.js-radio-rows tr', function() {
console.log('here2');
});
尝试如下:
$(document).ready(function () {
console.log('here1');
$('.js-radio-rows tr').on('click', function () {
console.log('here2');
});
});
或
$(document).ready(function () {
console.log('here1');
$(document).on('click', '.js-radio-rows tr', function () {
console.log('here2');
});
});
试试这个:
$(document).ready(function(){
console.log('here1');
$('.js-radio-rows').on('click', 'tr', function() {
console.log('here2');
});
})
最终代码:
<html>
<title>This is test</title>
<head>
<style>
</style>
</head>
<body>
<table class="table table-hover js-integrations js-radio-rows">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Owner</th>
<th>Modified Date</th>
</tr>
</thead>
<tbody>
<!-- Start load by ajax -->
<tr class="clickable">
<td class="js-integration-option">
<input type="radio" value="20" name="integration_id" class="pseudo-radio sr-only">
<label class="icon-lg" for="http-radio"></label>
</td>
<td>
<img align="absmiddle" src="imglocation" />
Some Title
<span class="file-size">
(50kb)
</span>
</td>
<td>
Owner Le Own
</td>
<td>
Date
</td>
</tr>
<!-- End load by ajax -->
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
console.log('here1');
$('.js-radio-rows').on('click', 'tr', function() {
console.log('here2');
});
})
</script>
</body>
</html>