Javascript JS can';不读取JS生成的行吗?
在HTML文件中,我使用JS生成表行以显示数据库返回的数据:Javascript JS can';不读取JS生成的行吗?,javascript,jquery,html,Javascript,Jquery,Html,在HTML文件中,我使用JS生成表行以显示数据库返回的数据: function appendResult(data) { var result = JSON.parse(data); var row = result.length; if (row == 0) { $("#productList").html("No matching result.");
function appendResult(data) {
var result = JSON.parse(data);
var row = result.length;
if (row == 0) {
$("#productList").html("No matching result.");
} else {
$("#productList").html("");
var i = 0;
while (i < row) {
// For each return record, create a new row, then write data into cell accordingly. New records are always written to last cell.
$("#productList").append("<tr class='hightLight'><td class='sku'></td><td class='productName'></td><td class='description'></td><td class='qtyPerCtn'></td><td class='weight'></td><td class='upc'></td><td class='gtin'></td><td class='vendorCode'></td><td class='note'></td></tr>");
$("td.sku").last().html(result[i]["sku"]);
$("td.productName").last().html(result[i]["productName"]);
$("td.description").last().html(result[i]["description"]);
$("td.qtyPerCtn").last().html(result[i]["qtyPerCtn"]);
$("td.weight").last().html(result[i]["masterWeightLb"]);
$("td.upc").last().html(result[i]["UPC"]);
$("td.gtin").last().html(result[i]["gtin"]);
$("td.vendorCode").last().html(result[i]["vendorCode"]);
$("td.note").last().html(result[i]["note"]);
i++;
}
}
}
但显然这不起作用。突出显示功能不起作用。但是,如果我将一行放在纯html中,它会起作用:
<table>
<tr class="hightLight"><td>test</td></tr>
</table>
测试
这是否意味着JS函数无法识别JS生成的元素?如何解决此问题?您必须使用委派,如下所示:
$(document).on("hover", ".hightLight", function () {
如果javascript在创建DOM之前就已经获得了源代码,它将看不到它。委派通过说“在文档
中查找悬停,如果悬停在.hightLight
中,则执行此操作…”来绕过它
您还可以将
文档
替换为.hightLight
的较近父级。看起来\productList
可能会很好地工作。您必须使用委托,如下所示:
$(document).on("hover", ".hightLight", function () {
如果javascript在创建DOM之前就已经获得了源代码,它将看不到它。委派通过说“在文档中查找悬停,如果悬停在.hightLight
中,则执行此操作…”
您还可以将文档
替换为.hightLight
。。。看起来,#productList
可能会很好地工作。即使在dom准备好后添加元素,这也可以工作:
// high light row when mouse roll over
$(document).ready(function () {
$("table")
.on('mouseenter', ".hightLight", function () {
$(this).addClass("highLightOnRollOver");
})
.on('mouseleave', ".hightLight", function () {
$(this).removeClass("highLightOnRollOver");
});
});
即使在dom就绪后添加元素,这也会起作用:
// high light row when mouse roll over
$(document).ready(function () {
$("table")
.on('mouseenter', ".hightLight", function () {
$(this).addClass("highLightOnRollOver");
})
.on('mouseleave', ".hightLight", function () {
$(this).removeClass("highLightOnRollOver");
});
});
谢谢你的简单解决方案。谢谢你的简单解决方案。