Javascript 如何修复:TypeError:document.querySelector(…)为空

Javascript 如何修复:TypeError:document.querySelector(…)为空,javascript,selectors-api,Javascript,Selectors Api,当我执行这段代码时,它不起作用。它正在返回: TypeError:document.querySelector(…)为空 但是,当我直接从函数内部使用字符串参数时,它是有效的 我尝试过将参数传递给函数参数中的queryselector,但失败 window.onload=changeText('lap0015','General Physics I') 功能更改文本(主题){ document.querySelector(`${subject}>.name`)。innerHTML=`${nam

当我执行这段代码时,它不起作用。它正在返回:

TypeError:document.querySelector(…)为空

但是,当我直接从函数内部使用字符串参数时,它是有效的

我尝试过将参数传递给函数参数中的queryselector,但失败

window.onload=changeText('lap0015','General Physics I')
功能更改文本(主题){
document.querySelector(`${subject}>.name`)。innerHTML=`${name}`
console.log('OK!')
}

//**尝试**几次后,我将脚本更改为jQuery: const name='Física Geral I' 常量代码='lap0015' $(文档).ready(getText) 函数getText(){ $(`${code}>p.code`).文本(`${code}`) $(`${code}>p.name`).文本(`${name}`)
}
我无法重新创建您的错误,但我已使您的代码正常工作。我只需将缺少的
name
参数添加到
changeText
函数中

window.onload=changeText('lap0015','General Physics I')
函数更改文本(主题、名称){
document.querySelector(`${subject}>.name`)。innerHTML=`${name}`
console.log('OK!')
}


您的
changeText
函数需要接受第二个参数
name

window.onload=changeText('lap0015','General Physics I')
函数更改文本(主题、名称){
document.querySelector(`${subject}>.name`)。innerHTML=name;
console.log('OK!')
}

试试这个:

$(document).ready(() => getText('lap0015', 'General Physics I'));
或者(如果您需要支持IE):


您在哪个浏览器中遇到了这个错误?Firefox 68.0.2(64位)仍然无法工作。在Chrome和Firefox中试用过。在Chrome中,我们有一个更长的答案:``script.js:4 Uncaught TypeError:无法在script.js:1 changeText@script.js:4(匿名)@script.js:1``中的changeText(script.js:4)处将属性'innerHTML'设置为null,这意味着在执行时,
document.querySelector(#lap0015>.name”)
找不到该元素。将该行替换为
console.log(!!document.getElementById(“lap0015”))
并告诉我们结果。经过多次尝试,我决定不再使用vanilla JS,而是使用JQuery。这是匿名函数的一个示例吗?或者是功能范式,或者是闭包?工作起来很有魅力!非常感谢。现在我可以用getText中的字符串替换解析的JSON数据了吗?我在这个目录中有一个Json文件,其中包含我课程中所有科目的所有数据。及时:存储库位于GIthub中,是公共的。github.com/vlaskz/dependency-chart
$(document).ready(function() { getText('lap0015', 'General Physics I'); });