[英]JavaScript querySelector error: 'Document': '[rowIndex=0]' is not a valid selector
I'm making a public library project where you can add books and remove them from a table.我正在制作一个公共图书馆项目,您可以在其中添加书籍并将它们从表格中删除。 I'm having trouble removing the table rows however.但是,我无法删除表格行。 To add the elements I have set it so that the remove button and the row have the same attribute number (btnIndex == rowIndex) and as you can see from below I'm trying to set it up so that the row is removed when the button is clicked.要添加我已经设置的元素,以便删除按钮和行具有相同的属性编号(btnIndex == rowIndex),正如您从下面看到的那样,我正在尝试设置它以便在删除时删除行按钮被点击。
function removeElement () {
let buttonAtt = this.getAttribute("btnIndex");
const deletedRow = document.querySelector(`[rowIndex=${buttonAtt}]`);
console.log(deletedRow);
table.removeChild(deletedRow);
}
However, when I add an element to the table and then I click the Remove button, I get this error.但是,当我向表中添加一个元素然后单击“删除”按钮时,会出现此错误。
Error:错误:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[rowIndex=0]' is not a valid selector.未捕获的 DOMException:无法在“文档”上执行“querySelector”:“[rowIndex=0]”不是有效的选择器。
I'm not sure what the problem exactly is.我不确定到底是什么问题。 I would really appreciate your help.我将衷心感谢您的帮助。 Thank you.谢谢你。
Wrap the attribute value you're targeting in quotes:将您定位的属性值用引号括起来:
function targetRowIndex(index) { document.querySelector(`[rowIndex="${index}"]`).style.background = "red"; } document.querySelector('button').addEventListener('click', function() { targetRowIndex(0); });
<div rowIndex=0>Content here</div> <button>Run function →</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.