How to fix: TypeError: document.querySelector(...) is null

How to fix: TypeError: document.querySelector(...) is null

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

TypeError: document.querySelector(...) is null.

但是,当我直接从函数内部使用字符串参数时,它起作用了。

我尝试过在函数参数中向 queryselector 传递参数,但失败了。

window.onload = changeText('lap0015', 'General Physics I')

function changeText(subject) {
  document.querySelector(`#${subject} > .name`).innerHTML = `${name}`
  console.log('OK!')
}
<div id="lap0015" class="subject">
  <p class="code"></p>
  <p class="name"></p>
  <p class="theory"></p>
  <p class="practice"></p>
  <p class="totalHourLoad"></p>
</div>


// **After** some tries, I changed my script to jQuery:

const name = 'Física Geral I'
const code = 'lap0015'

$(document).ready(getText)

function getText() {
$(`#${code} > p.code`).text(`${code}`)
$(`#${code} > p.name`).text(`${name}`)
}

.ready(getText 'here') 中没有括号时,如何以编程方式将参数传递给 getText?

实际的结果就是上面给出的错误。预期结果应该是这样的:

print

我无法重现您的错误,但您的代码可以正常工作。我只需要将缺少的 name 参数添加到 changeText 函数。

window.onload = changeText('lap0015', 'General Physics I')

function changeText(subject, name) {
  document.querySelector(`#${subject} > .name`).innerHTML = `${name}`
  console.log('OK!')
}
<div id="lap0015" class="subject">
  <p class="code"></p>
  <p class="name"></p>
  <p class="theory"></p>
  <p class="practice"></p>
  <p class="totalHourLoad"></p>
</div>

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

window.onload = changeText('lap0015', 'General Physics I')

function changeText(subject, name) {
  document.querySelector(`#${subject} > .name`).innerHTML = name;
  console.log('OK!')
}
<div id="lap0015" class="subject">
  <p class="code"></p>
  <p class="name"></p>
  <p class="theory"></p>
  <p class="practice"></p>
  <p class="totalHourLoad"></p>
</div>

试试这个:

$(document).ready(() => getText('lap0015', 'General Physics I'));

或者(如果需要支持IE):

$(document).ready(function() { getText('lap0015', 'General Physics I'); });