[英]Why is this not assigning data to a variable declared outside the function
Been messing around trying to get this to work, as you can see in the code below when the table row is selected then it outputs an alert of which row they selected and also assigns the row's id to a variable declared outside of the method. 正如您在下面的代码中看到的那样,当选中表行时,您一直在搞怪,以使其工作,然后输出警告,告知他们选择了哪一行,并将该行的ID分配给在方法外部声明的变量。 I'm using this variable to be able to manipulate the data.
我正在使用此变量来处理数据。
However, when it reaches another function the variable is undefined. 但是,当它到达另一个函数时,该变量未定义。 "Uncaught TypeError: Cannot read property 'parentElement' of undefined".
“未捕获的TypeError:无法读取未定义的属性'parentElement'”。 Where and how should this variable be declared in order for me to be able to manipulate the data which is generated by the tables?
为了使我能够操作由表生成的数据,应在何处以及如何声明此变量?
var selectedItem;
function deleteRow() {
selectedItem.parentElement.removeChild(selectedItem);
}
Code snippet from inside function where the rows are created. 来自创建行的内部函数的代码片段。 See "Makes rows selectable:
请参阅“使行可选:
var tr = document.getElementById("c_row" + r);
for (var c = 0; c < columns; c++)
{
var td = document.createElement("td");
td.innerText = cellText[c];
tr.appendChild(td);
//Makes the rows selectable
tr.onclick = function(event) {
alert('Clicked: ' + event.target.parentNode.id)
selectedItem = event.target.parentNode.id;
}
}
You need a js element ... selectedItem
is a string 您需要一个js元素...
selectedItem
是一个字符串
function deleteRow() {
document.getElementById(selectedItem).parentElement.removeChild(selectedItem);
}
.id
is a string, so it doesn't have a .parentNode
property. .id
是一个字符串,因此没有.parentNode
属性。 Instead assign the element directly. 而是直接分配元素。
selectedItem = event.target.parentNode;
And if it's the row itself that you're trying to assign, then just use this
instead. 如果您要分配的是行本身,则只需使用
this
。
selectedItem = this;
And if the variable is undefined, then it is likely that there has not yet been a click. 并且,如果变量未定义,则很可能尚未点击。 So you should check before trying to remove.
因此,您应在尝试删除之前进行检查。
function deleteRow() {
if (selectedItem) {
selectedItem.parentElement.removeChild(selectedItem);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.