编辑 - 已解决 //正如用户Win在答案中指出的那样,如果某个函数被命名为click并且您尝试使用HTML按钮调用它,那么它会将该函数与内置函数混淆/标准“单击()”按钮用于HTML按钮
任何人都能弄清楚,为什么(在世界上)这不起作用?我在Chrome,IDE和/或JSFiddle中都没有错误报告。
HTML
<!DOCTYPE html>
<html>
<head>
<script src="app.js"></script>
</head>
<body>
<input id="search" type="text" name="input" placeholder="Search..">
<button onclick="click()" value="Submit">Get weather</button>
</body>
</html>
的JavaScript
function click() {
if (document.getElementById("search").value == "New York") {
console.log("Loading weather for New York...");
} else {
console.log("City name isn't valid. Try again");
}
}
JSFiddle:https://jsfiddle.net/nd6f5pp7/
提前致谢。
答案 0 :(得分:5)
不要点击该功能,它会与obj原型混淆。
// Grab Input from DOM
var iptSearch = document.getElementById('search')
// Grab Submit button from DOM
var btnGetWeather = document.getElementById('get-weather');
// Add Event Listener
btnGetWeather.addEventListener('click', function() {
if (iptSearch.value === "New York") {
console.log("Loading weather for New York...");
} else {
console.log("City name isn't valid. Try again");
}
});
&#13;
<input id="search" placeholder="Search..."/>
<button id="get-weather">Get Weather</button>
&#13;
或者,如果您想要遵循您给出的示例代码。使用以下内容:
function getWeather() {
if (document.getElementById('search').value === "New York") {
console.log("Loading weather for New York...");
} else {
console.log("City name isn't valid. Try again");
}
}
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="app.js"></script>
</head>
<body>
<input id="search" type="text" name="input" placeholder="Search..">
<button onclick="getWeather()">Get weather</button>
</body>
</html>
&#13;