Javasctipt function running without being called? [duplicate]

允我心安 提交于 2019-12-24 06:05:31

问题


So I only have 6 lines of code in my page.js file and they are:

document.getElementById("desired").addEventListener("blur", gradeChange());
document.getElementById("calculate").addEventListener("click", gradeChange());

function gradeChange() {                                                              
    var dog = document.getElementById("desired").value;                               
    console.log(dog);                                                                 
}

And in my page.html I have:

<input id="desired" type="text">

and somewhere else:

<button id="calculate" type="button">Calculate</button>

I thought it would work without the button, so that when I typed something in the textbox and then left the textbox, it would show up in the log. But nothing showed up, so I added the button to make it more straight forward. Still, it did nothing in the log. Any idea why nothing is showing up?


回答1:


gradeChange() calls the function gradeChange

document.getElementById("desired").addEventListener("blur", gradeChange());
document.getElementById("calculate").addEventListener("click", gradeChange());

Change gradeChange() to gradeChange

document.getElementById("desired").addEventListener("blur", gradeChange);
document.getElementById("calculate").addEventListener("click", gradeChange);


来源:https://stackoverflow.com/questions/27559438/javasctipt-function-running-without-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!