【问题标题】:referencing the id of a div [closed]引用 div 的 id [关闭]
【发布时间】:2015-11-12 16:01:19
【问题描述】:

我正在尝试引用变量 thisId 中 div 表行的 id。当我console.log(thisId) 时,它说thisIdundefined。我做错了什么?

$('.deleteButton').click(function(){
    var thisId = $(this).parent().parent().id;
    for (var i = 0; i < tableData.length; i++) {
        if (tableData[i].rowValue === thisId) {
            tableData.splice(thisId, 1);
        }
    }
    $(this).parent().parent().remove();
});
}
}

HTML

"<div id='" + tableData[i].rowValue + "' class=\"Row\">" +
                            "<div class=\"Cell\">" +
                            "<p>" + tableData[i].textInput + "</p>" +
                        "</div>" +
                        "<div class=\"Cell\">" +
                            "<p>" + tableData[i].perIntervalInput + "</p>" +
                        "</div>" +
                        "<div class=\"Cell\">" +
                            "<p>" + tableData[i].radioInput + "</p>" +
                        "</div>" +
                        "<div class=\"Cell\">" +
                            "<button class=\"deleteButton\">Delete</button>" +
                        "</div>" +
                        "</div>"

【问题讨论】:

标签: javascript jquery arrays


【解决方案1】:

ID 是一个属性,因此可以通过attr(..) 函数引用。

var thisId = $(this).parent().parent().attr("id");

【讨论】:

  • 也尝试了 .attr,结果相同。
  • 正如其他人所提到的,您需要扩展您的问题。我们需要查看您正在使用的 HTML 以及它如何引用您的 JS。
  • 刚刚添加了html(看起来很乱,因为它正在被附加)
  • 如果上面的代码仍然无法运行,那么您的脚本似乎一定有其他问题。作为检查,试试console.log($(this).parent().parent().get(0).outerHTML); 看看它是否真的是你期望的代码。
【解决方案2】:

由于您使用的是 jQuery,因此您可以使用:

var thisId = $(this).parent().parent().attr('id');

但是您的 HTML 并不是为了向我们展示您实际引用的内容,以及您是否正确引用它,因此可能还有其他原因。

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2016-10-06
    • 2013-12-23
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多