为什么会出现错误“ button.addEventListener不是函数”

时间:2018-07-14 13:20:00

标签: javascript syntax-error addeventlistener

有人可以告诉我为什么我收到带有以下代码的上述错误消息吗?

尽管似乎不想在浏览器中运行,但它在jsfiddle上可以正常工作。

var bladeRunnerButton = document.querySelector("ul.bladeRunner").innerHTML;
var bladeRunnerContent = document.querySelector("div.bladeRunner").innerHTML;

var detroitButton = document.querySelector("ul.detroit").innerHTML;
var detroitContent = document.querySelector("div.detroit").innerHTML;

var mammejongButton = document.querySelector("ul.mammejong").innerHTML;
var mammejongContent = document.querySelector("div.mammejong").innerHTML;

var buttonArray = [bladeRunnerButton, detroitButton, mammejongButton];
var articleArray = [bladeRunnerContent, detroitContent, mammejongContent];



function createfunc(i) {
    return function() { document.getElementById("fillPane").innerHTML = articleArray[i];};
}


for (let i=0; i < articleArray.length; i++) {
let button = buttonArray[i];
button.addEventListener("click", createfunc(i));
}
#content {
  display: none;
}
<li>
<ul class="bladeRunner">Blade Runner 2049</ul>
<ul class="detroit">Detroit</ul>
<ul class="mammejong">Mammejong</ul>
</li>

<div class="contentPanel bladeRunner">
</div>

<div class="contentPanel detroit">
</div>

<div class="contentPanel mammejong">
</div>

1 个答案:

答案 0 :(得分:2)

您应以Element而非innerHTML为目标来附加事件。因此,请从以下内容中删除innerHTML

var bladeRunnerButton = document.querySelector("ul.bladeRunner");
var detroitButton = document.querySelector("ul.detroit");
var mammejongButton = document.querySelector("ul.mammejong");

工作代码示例,对代码进行了少量修改:

var bladeRunnerButton = document.querySelector("ul.bladeRunner");
var bladeRunnerContent = document.querySelector("div.bladeRunner").innerHTML;

var detroitButton = document.querySelector("ul.detroit");
var detroitContent = document.querySelector("div.detroit").innerHTML;

var mammejongButton = document.querySelector("ul.mammejong");
var mammejongContent = document.querySelector("div.mammejong").innerHTML;

var buttonArray = [bladeRunnerButton, detroitButton, mammejongButton];
var articleArray = [bladeRunnerContent, detroitContent, mammejongContent];

function createfunc(i) {
  document.getElementById("fillPane").innerHTML = articleArray[i];
}

for (let i=0; i < articleArray.length; i++) {
  let button = buttonArray[i];
  button.addEventListener("click", function(){createfunc(i)});
}
.contentPanel {
  display: none;
}
<li>
  <ul class="bladeRunner">Blade Runner 2049</ul>
  <ul class="detroit">Detroit</ul>
  <ul class="mammejong">Mammejong</ul>
</li>

<div class="contentPanel bladeRunner">Blade Runner</div>
<div class="contentPanel detroit">Detroit</div>
<div class="contentPanel mammejong">Mammejong</div>

<div id="fillPane"></div>