如果/ else带按钮和输入

the*_*tem 2 html javascript input function button

EDIT - 已解决 //正如用户Win在答案中指出的那样,如果一个函数被命名为click并且您尝试使用HTML按钮调用它,那么它会将该函数与HTML的内置/标准"click()"函数混淆纽扣

任何人都可以弄清楚,为什么(世界上)这不起作用?我在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>
Run Code Online (Sandbox Code Playgroud)

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");
  }
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle:https://jsfiddle.net/nd6f5pp7/

提前致谢.

Win*_*Win 5

不要调用函数click,它会与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");
  }
});
Run Code Online (Sandbox Code Playgroud)
<input id="search" placeholder="Search..."/>
<button id="get-weather">Get Weather</button>
Run Code Online (Sandbox Code Playgroud)

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

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");
  }
}
Run Code Online (Sandbox Code Playgroud)
<!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>
Run Code Online (Sandbox Code Playgroud)