[英]why i'm getting a querySelectorAll() error
i tried to implement a document.getElementsByAttribute function and i came with this : 我试图实现document.getElementsByAttribute函数,但我附带了以下内容:
function getElementsByAttribute(att, val){
return document.querySelectorAll(`[${att} = ${val}]`)
}
but why i get an error when i try to type the return statement directly on the console : 但是为什么当我尝试直接在控制台上键入return语句时出现错误:
document.querySelectorAll("["id" = "btn"]")
is it not the same like getElementsByAttribute2('id', 'btn')
? 与
getElementsByAttribute2('id', 'btn')
吗?
but why i get an error when i try to type the return statement directly on the console :
但是为什么当我尝试直接在控制台上键入return语句时出现错误:
document.querySelectorAll("["id" = "btn"]")
Because what you are typing into the console is not the same as what you have in your function. 因为您在控制台中输入的内容与您在功能中所拥有的不同。 Your function uses template literals :
您的函数使用模板文字 :
document.querySelectorAll(`[${att} = ${val}]`)
And, template literals can be inserted directly into regular literal strings without having to worry about quoting them or concatenating them with the rest of the string. 而且,模板文字可以直接插入到常规文字字符串中,而不必担心引用它们或将它们与字符串的其余部分连接在一起。
When you enter directly into the console, you didn't use template literals, you just used a literal and in that case quotes and concatenation matter. 直接输入控制台时,您没有使用模板文字,而只是使用文字,在这种情况下,引号和连接很重要。 Quotes come in pairs, so the first pair is:
"["
and that is immediately followed by id
and because you didn't concatenate the two parts like this: 引号是成对出现的,因此第一对是:
"["
,其后紧跟id
,因为您没有将这两个部分串联在一起:
"[" + id
It throws an error - probably something like unexpected identifier
. 它将引发错误-可能类似于
unexpected identifier
。
The CSS attribute selector should take the form of: CSS属性选择器应采用以下形式:
[attributeName comparisonOperator value]
Quotes around the value are only necessary if the value has spaces in it. 仅当值中包含空格时,才需要在值周围加上引号。 So you could just write:
所以你可以这样写:
document.querySelectorAll("[id=btn]");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.