如果/ else有按钮和输入

时间:2017-07-30 14:36:47

标签: javascript html function button input

编辑 - 已解决 //正如用户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/

提前致谢。

1 个答案:

答案 0 :(得分:5)

不要点击该功能,它会与obj原型混淆。

&#13;
&#13;
// 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;
&#13;
&#13;

或者,如果您想要遵循您给出的示例代码。使用以下内容:

&#13;
&#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;
&#13;
&#13;