小码哥的IT人生

onsearch 事件

JavaScript基础 2022-06-08 12:02:41小码哥的IT人生shichen

onsearch 事件

实例

提交搜索时执行 JavaScript:

<input type="search" onsearch="myFunction()">

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>请在搜索字段中输入一些内容,然后按“ENTER”。</p>
<input type="search" id="myInput" onsearch="myFunction()">
<p><b>注释:</b>Internet Explorer、Firefox 或 Opera 12 及更早版本不支持 onsearch 事件。</p>
<p id="demo"></p>
<script>
function myFunction() {
   var x = document.getElementById("myInput");
   document.getElementById("demo").innerHTML = "You are searching for: " + x.value;
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

定义和用法

当用户按下 "ENTER" 键或点击 type="search" 的 <input> 元素中的 "x" 按钮时,就会发生 onsearch 事件。

浏览器支持

表中的数字注明了完全支持该事件的首个浏览器版本。

事件 Chrome IE Firefox Safari Opera
onsearch 支持 不支持 不支持 支持 15.0

语法

在 HTML 中:

<element onsearch="myScript">

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例演示如何将 "onsearch" 事件分配给 input 元素。</p>
<p>请在搜索字段中输入一些内容,然后按“ENTER”。</p>
<input type="search" id="myInput" onsearch="myFunction()">
<p><b>注释:</b>Internet Explorer、Firefox 或 Opera 12 及更早版本不支持 onsearch 事件。</p>
<p id="demo"></p>
<script>
function myFunction() {
   var x = document.getElementById("myInput");
   document.getElementById("demo").innerHTML = "You are searching for: " + x.value;
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

在 JavaScript 中:

object.onsearch = function(){myScript};

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例使用 HTML DOM 将 "onsearch" 事件分配给 input 元素。</p>
<p>请在搜索字段中输入一些内容,然后按“ENTER”。</p>
<input type="search" id="myInput">
<p><b>注释:</b>Internet Explorer、Firefox 或 Opera 12 及更早版本不支持 onsearch 事件。</p>
<p id="demo"></p>
<script>
document.getElementById("myInput").onsearch = function() {myFunction()};
function myFunction() {
  var x = document.getElementById("myInput");
  document.getElementById("demo").innerHTML = "You are searching for: " + x.value;
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

在 JavaScript 中,使用 addEventListener() 方法:

object.addEventListener("search", myScript);

完整实例:

<!DOCTYPE html>
<html>
<body>
<p>本例使用 addEventListener() 方法将 "search" 事件附加到 input 元素。</p>
<p>请在搜索字段中输入一些内容,然后按“ENTER”。</p>
<input type="search" id="myInput">
<p><b>注释:</b>Internet Explorer、Firefox 或 Opera 12 及更早版本不支持 search 事件。</p>
<p id="demo"></p>
<script>
document.getElementById("myInput").addEventListener("search", myFunction);
function myFunction() {
  var x = document.getElementById("myInput");
  document.getElementById("demo").innerHTML = "You are searching for: " + x.value;
}
</script>
</body>
</html>

可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html

注释:Internet Explorer 8 或更早的版本不支持 addEventListener() 方法

技术细节

冒泡: 不支持
可取消: 不支持
事件类型: Event
支持的 HTML 标签: <input type="search">
DOM 版本: Level 3 Events

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024