为什么我的表tr单击函数没有在jQuery中调用?
我想获得使用jQuery的表行的值。当我在控制台上尝试相同的jQuery代码,并尝试点击后,即选择该行并给予我期望的正确值。但我不知道为什么它不是从我的JavaScript文件运行。但是其他功能都工作在同一个JavaScript文件为什么我的表tr单击函数没有在jQuery中调用?
$(".chequeTable tbody tr").click(function() {
alert('Vendor ID ==');
$('.selected').removeClass('selected');
$(this).addClass("selected");
alert('Vendor ID ==' + $('.tdVendorID').html());
$(this).css("background-color", "#000000");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover FilterTable chequeTable table-striped" id="queryTable">
<thead>
<tr>
<th>S.No</th>
<th>VendorID</th>
<th>VendorName</th>
<th>ReqNo</th>
<th>ChequeAmount</th>
<th>VendorBalance</th>
<th>Balance</th>
<th>Description</th>
<th>StockValue</th>
<th>Yes/No</th>
</tr>
</thead>
<tbody>
<tr class="">
<td class="tdSno">1</td>
<td class="tdVendorID">6000 </td>
<td class="tdVendorName">john</td>
</tr>
</tbody>
</table>
最有可能的表是不存在的,当你在初始化jQuery的click事件。你动态地建立表格吗?
尝试单击事件绑定表中,而不是直接的TR:
$(".chequeTable").on("click", "tr", function() { ... });
当table.chequeTable是在HTML里,才能工作。
一些解释为什么:
jquery documentation for on()
它说,它结合了事件中选择所有元素。这意味着,不在选择器中的元素(例如任何尚未存在的tr)将不会收到该事件。为此,您必须绑定容器上的点击事件并检查点击的子元素是什么。这是反正更多perfomant因为只连接一个click事件,而不是100秒(如果你有数百个TR-元素)
是的,当我加载页面时,该表没有任何行。我正在动态添加行 –
是的你是正确的。你的代码正在工作。你能告诉我为什么它不适用于我的jQuery代码?它不会工作如果我动态添加行? –
我编辑了我的答案,稍微解释一下。希望能帮助到你 :) – cloned
在这里,你有一个解决方案去
$("table.chequeTable").on('click', 'tr', function() {
alert('Vendor ID ==');
$('.selected').removeClass('selected');
$(this).addClass("selected");
alert('Vendor ID ==' + $('.tdVendorID').html());
$(this).css("background-color", "#000000");
});
$('tbody').append(`<tr class="">
<td class="tdSno">1</td>
<td class="tdVendorID">6000 </td>
<td class="tdVendorName">john</td>
</tr>`);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover FilterTable chequeTable table-striped" id="queryTable">
<thead>
<tr>
<th>S.No</th>
<th>VendorID</th>
<th>VendorName</th>
<th>ReqNo</th>
<th>ChequeAmount</th>
<th>VendorBalance</th>
<th>Balance</th>
<th>Description</th>
<th>StockValue</th>
<th>Yes/No</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
您需要做你的行动态生成事件委托。
参考文档:Event delegation
希望这会帮助你。
你的代码是独立工作的,所以这个问题一定是由于我们看不到你的代码库中的其他错误。检查控制台是否有错误。 –
检查浏览器控制台 – Amit
@RoryMcCrossan我检查了我的控制台。它不显示任何错误 –