javascript Element.querySelector 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33323840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Element.querySelector is undefined
提问by Bill Bllson
Why does this code throw an error in the console reading TypeError: pizzaBox.querySelector is not a function. (In 'pizzaBox.querySelector('h6')', 'pizzaBox.querySelector' is undefined)
?
为什么此代码会在控制台读取中引发错误TypeError: pizzaBox.querySelector is not a function. (In 'pizzaBox.querySelector('h6')', 'pizzaBox.querySelector' is undefined)
?
function addToppingsToAll (toppings)
{
var pizzaBoxHolder = document.getElementById("PizzaBoxHolder");
var PizzaBoxList = pizzaBoxHolder.childNodes;
for ( var i = 0 ; i < pizzaBoxList.length ; i++ )
{
var pizzaBox = pizzaBoxList[i];
toppingList = pizzaBox.querySelector('h6');
toppingList.textContent = "You have " + toppings " on your pizza";
}
}
采纳答案by jfriend00
There are at least three isssues in your code:
您的代码中至少存在三个问题:
- You are probably iterating through some text nodes which don't have a
.querySelector()
method. - You are not initializing your
for
loop iteration variablei
- You have an undeclared variable
lineBoxList
you are attempting to use.
- 您可能正在遍历一些没有
.querySelector()
方法的文本节点。 - 您没有初始化
for
循环迭代变量i
- 您
lineBoxList
尝试使用一个未声明的变量。
You can simplify things by just using .querySelectorAll()
and letting the selector do more of the work for you.
您可以通过使用.querySelectorAll()
并让选择器为您完成更多工作来简化事情。
function addToppingsToAll (toppings) {
var toppingItems = document.querySelectorAll("#PizzaBoxHolder h6");
for (var i = 0; i < toppingItems.length; i++) {
toppingItems[i].textContent = "You have " + toppings " on your pizza";
}
}
回答by Quentin
querySelector
is a method that appears on HTML Element Nodes. One or more of the childNodes
must be some kind of node that is not an Element (such as Text Nodes or Comment Nodes).
querySelector
是一种出现在 HTML 元素节点上的方法。其中一个或多个childNodes
必须是某种非元素的节点(例如文本节点或注释节点)。
This is probably most easily resolved with:
这可能最容易解决:
var PizzaBoxList = document.querySelector("#PizzaBoxHolder > *");