为什么函数在被追加时返回为null,或者设置为textContent?

时间:2018-05-11 17:28:36

标签: javascript function

我想不通的东西,想要找到解决方案的原因。

const print_html = (param) => {
  let container = document.querySelector('Container');
  console.log(test_function(param)); // Why does this log the string?
  container.textConent = test_function(param) // ... But the function is null here?
}

const test_function = (name) => {
  return `My name is ${name}`;
};

print_html('Jermaine')

具有控制台日志的行将按预期将正确的字符串打印到控制台,但是下面的行如何才能将容器的textContent设置为字符串?

1 个答案:

答案 0 :(得分:0)

您在textContent中输入了您的查询选择器错误,它应该是.container

const print_html = (param) => {
  let container = document.querySelector('.container');
  console.log(test_function(param)); // Why does this log the string?
  container.textContent = test_function(param) // ... But the function is null here?
}

const test_function = (name) => {
  return `My name is ${name}`;
};

print_html('Jermaine')
<div class="container"></div>

修改

正如Icepickle指出的那样,如果使用的HTML标记是Container

,则查询选择器<Container></Container>可以是正确的