javascript - 单击后无法从搜索栏中获取属性 'value'

标签 javascript html css

按下搜索按钮后,我的代码应该将搜索栏的输入保存到一个变量中并将其附加到 Google 链接。该函数应仅在按下按钮时执行。

我以前是成功的,但那次唯一的不同是我把“onclick”放在了 HTML 标签中。这段代码似乎不起作用,因为尽管尚未单击按钮,但函数 searchExplore() 已执行,因此使搜索输入的值等于 null 或未定义。

当我使用 Google Dev Tools 调试它时,它立即给我一个错误:

Unable to get property 'value' of undefined or null reference

这发生在我点击按钮之前。

document.getElementById('searchbtn').onclick = searchExplore();

function searchExplore(){
 var input = document.getElementById('searchbar').value;
 document.getElementById('searchform').action = "https://www.google.com/search?q="+input;
}
body{
}
.search{
  text-align:center;
  background: url("http://dash.ga.co/assets/anna-bg.png");
  background-size:cover;
  background-position: center;
  padding:20px;
  }
form{
  display:inline-flex;
}
#searchbar{
  font-size:35px;
  border: 0;
  padding: 0px 0 0 20px;
  border-radius:20px 0 0 20px;
  outline: 0;
  font-family: 'Bitter', serif;
  }
#searchbtn{
  font-size:35px;
  border: 0;
  padding: 10px;
  border-radius: 0 20px 20px 0;
  outline: 0;
  width: 90px; 
  cursor: pointer;
}

#searchbar:hover,#searchbar:focus{
  box-shadow:-3px 3px 15px;
}
#searchbtn:hover,#searchbtn:focus{
  box-shadow:-.1px 3px 15px 1px;
}
<!DOCTYPE html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Bitter" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
  <link rel="stylesheet" href="mypen1.css" type="text/css"/>
  <title>MJ Search</title>
  <script type="text/javascript" src="mypen1.js"></script>
</head>
<body>
  <div class="search">
    <form id="searchform" action="">
         <input id="searchbar" type= "search" placeholder="Search & Explore..."/>
         <button id="searchbtn"><i class="fa fa-search"></i></button>
    </form>
  </div> 
</body>    

最佳答案

问题是这一行。

document.getElementById('searchbtn').onclick = searchExplore();

您正在调用 searchExplore,然后将结果返回给 onclick 处理程序。

您可能想将函数本身分配给 onclick 处理程序 - 所以不要在此处调用您的函数。

document.getElementById('searchbtn').onclick = searchExplore;

关于javascript - 单击后无法从搜索栏中获取属性 'value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47825016/

相关文章:

javascript - 如何按字母顺序对 div 进行排序,同时保持 div 的形式?

html - 将元素放在 div 的中心

html - 是否可以创建检测当前 URL 的 CSS/SASS mixin?

php - 以与保存时相同的模式显示 mysql 结果

javascript - jQueryUI Sortable - 取消属性使无法编辑输入

javascript - 使用 jquery 添加 div 边框而不更改宽度和默认边框

jquery - .hover 在 .click 插入时不再起作用

javascript - Controller 可以提供 json 或 html

javascript - 我想让 model[i].marker.addListener ('click' , function() { 在 for 循环之外

javascript - 创建新数组和清除长度之间的区别