按钮addEventListener不起作用

时间:2017-07-12 14:08:33

标签: javascript html addeventlistener

我在按钮工作时遇到问题。当我点击这个按钮时,我想要发生一些事情:

<button id="pigBtn" value="click">Pig It!</button> 

我的JS文件有

window.addEventListener('load', function(){
    console.log('hello'); 
    let pigBtn = document.querySelector('#pigBtn'); 
    console.log('pigged'); 
    pigBtn.addEventListener('click', function (){

    function pigIt(phrase) {
        let array = phrase.split(' '); 
        console.log('array'); 

        for (let i = 0; i < phrase.length; i++) {
            let pig = array[i].split(''); 
            let one = pig.shift(); 
            pig.push(one); 
            pig.push('ay'); 
            let two = pig.join(''); 

            array[i] = two; 
    }
        return array.join(' '); 

    }

  }); 

}); 

&#39;你好&#39;并且&#39;清空&#39;出现但是&#39;阵列&#39;才不是。我在这里缺少什么?

3 个答案:

答案 0 :(得分:0)

该按钮的ID为pigBtn,但您尝试选择ID为pigged的元素。

请改为尝试:

let pigBtn = document.querySelector('#pigBtn');

&#13;
&#13;
window.addEventListener('load', function(){
   console.log('hello'); 
   let pigBtn = document.querySelector('#pigBtn'); 
   console.log('pigged'); 
   pigBtn.addEventListener('click', function (){
      console.log('clicked'); 
   }); 
});
&#13;
<button id="pigBtn" value="click">Pig It!</button> 
&#13;
&#13;
&#13;

答案 1 :(得分:0)

window.addEventListener('load', function(){
  console.log('hello'); 
  let pigBtn = document.querySelector('#pigBtn'); 
  console.log('pigged');

  pigBtn.addEventListener('click', function (){
    console.log('clicked'); 
  }); 
});

querySelector中的ID必须与HTML中按钮的ID相匹配。 https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

答案 2 :(得分:0)

您的pigIt函数永远不会执行。您可以在事件处理程序中定义它,但是从不运行它。

我认为你正在寻找这样的事情:

&#13;
&#13;
window.addEventListener('load', function(){
  var sentence = "This is the phrase I'm pigging";
  console.log('hello'); 
  let pigBtn = document.getElementById('pigBtn'); 
  let pigTxt = document.getElementById('phraseTxt'); 
  let pigPhraseTxt = document.getElementById('pigPhraseTxt'); 
  console.log('pigged'); 
  pigBtn.addEventListener('click', function(e) {
    let array = pigTxt.value.split(' '); 
    for (let i = 0; i < array.length; i++) {
      let pig = array[i].split(''); 
      let one = pig.shift(); 
      pig.push(one); 
      pig.push('ay'); 
      let two = pig.join('');
      array[i] = two; 
    }
    pigPhraseTxt.value = array.join(' '); 
  });
}); 
&#13;
input {
  display : block;
  width : 100%;
  padding: 0;
  border: 1px solid #aaa;
}

input:read-only {
    background: #ddd;
}
&#13;
<input type="text" id="phraseTxt" value="This is the text I'm converting to Pig Latin" />
<input type="text" id="pigPhraseTxt" readonly />
<button id="pigBtn" value="click">Pig It!</button> 
&#13;
&#13;
&#13;