单击按钮或单击发送按钮后,将发生以下情况:
HTML超级简化代码:
<!DOCTYPE html>
<html>
<body>
<!-- Page Preloder -->
<!-- Header section -->
<header class="header-section">
<form class="header-search-form">
<input id= "searchBarP" type="text" placeholder="Search on divisima ....">
<button id= "searchIconP"><i class="flaticon-search"></i></button>
<script>
var searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
</script>
</form>
</header>
<!-- Header section end -->
</body>
</html>
在单击按钮之前会发生以下情况:
之后:
答案 0 :(得分:0)
您的按钮没有type,在这种情况下,默认类型是“提交”。由于您也未指定form's method,因此默认为GET。此方法会将所有参数附加到问号后的URL上,这就是单击按钮后看到它的原因。
解决方案1:
如果您希望按钮和搜索栏都执行相同的操作,请监听Submit事件:
<form class="header-search-form" id="form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const form = document.getElementById("form");
form.addEventListener("submit", function(e) {
e.preventDefault();
alert("Trial");
});
</script>
</form>
解决方案2:
将按钮的类型设置为“按钮”,以防止其提交表单。
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="button" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchBarP = document.getElementById("searchBarP");
searchBarP.addEventListener("searchP", function() {
alert("Trial");
});
</script>
</form>
请记住,您的searchP
侦听器将无法工作,因为没有名为“ searchP”的事件。如果您想区分在搜索栏中键入内容时单击按钮并单击“输入”的行为,则可以执行以下操作:
<form class="header-search-form">
<input id="searchBarP" type="text" placeholder="Search on divisima ....">
<button type="submit" id="searchIconP"><i class="flaticon-search"></i></button>
<script>
const searchIconP = document.getElementById("searchIconP");
const searchBarP = document.getElementById("searchBarP");
searchIconP.addEventListener("click", function(e) {
e.preventDefault(); //Remove this if you want to submit the form when you click the button
alert("Button click");
});
searchBarP.addEventListener("keydown", function(e) {
if (e.keyCode === 13){
alert("Search bar enter hit");
e.preventDefault(); //Remove this if you want to submit the form when you hit enter while typing in the search bar
}
});
</script>
</form>
答案 1 :(得分:0)
searchBarP.addEventListener("searchP",function(){
alert("Trial");
});
addEventListener
的第一个参数应为event
。您拥有searchP
这是元素。尝试改用click
。