JS可以't读取JS生成的行

JS can't read a row generated by JS?

本文关键字:JS 读取 可以      更新时间:2023-09-26

在HTML文件中,我使用JS生成表行,以显示数据库返回的数据:

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++;
                    }
                }
            }

然后我有一个功能可以在鼠标滚动时突出显示行:

// high light row when mouse roll over
$(document).ready(function () {
    $(".hightLight").hover(function () {
        $(this).addClass("highLightOnRollOver");
    }, function () {
        $(this).removeClass("highLightOnRollOver");
    });
});

但显然这是行不通的。高亮显示功能不起作用。但如果我把一行放在纯html中,它就行了:

<table>
<tr class="hightLight"><td>test</td></tr>
</table>

这是否意味着JS函数无法识别JS生成的元素?我该如何解决这个问题?

即使在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");
        });
});

您必须使用委派,如下所示:

    $(document).on("hover", ".hightLight", function () {

如果javascript是在创建DOM之前来源的,它就看不到它了。Delegation绕过它说"在document中查找悬停,如果悬停在.hightLight中,那么就这样做…

您也可以用.hightLight的更接近的父代来替换document。。。看起来CCD_ 5可能工作得很好。