如何在单个HTML文本字段上应用多个事件

How to apply multiple events on single HTML text field?

本文关键字:应用 事件 字段 文本 单个 HTML      更新时间:2023-09-26

我想通过多个事件onBluronKeyuponClick调用一个函数,但我的脚本只处理第一个事件。

我的代码:

<input type="text" onBlur="getprice(this),getdesc(this)" onClick="getprice(this),getdesc(this)" id="item" name="item[]">
<input type="text" onBlur="getprice(this);getdesc(this)" onClick="getprice(this);getdesc(this);" id="item" name="item[]">

当您将函数内联签名到dom元素时,请记住,在双引号内,您正在编写javascript代码。因此,对于每个函数,都应该有一个";"作为结尾,快乐编码兄弟!

看看下面的代码,我在其中定义了var events中的目标事件。您可以在那里添加多个事件以添加到您的功能中。

您可以在浏览器Console中检查输出。

控制台输出

__EVENT__ click
__getPrice__ Empty
__getDesc__ Description
__EVENT__ blur
__getPrice__ Ok
__getDesc__ Description
__EVENT__ click
__getPrice__ Ok
__getDesc__ Description
__EVENT__ click
__getPrice__ 9874521
__getDesc__ Description
__EVENT__ blur
__getPrice__ 9874521
__getDesc__ Description

代码段

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <title>Attach Multiple Events</title>
  <style>
    input[type="text"] {
      border: none;
      outline: none;
    }
  </style>
</head>
<body>
  <input type="text" id="textInput" name="textInput[]" placeholder="Write your input...">
  <script>
    (function() {
      // Define variables
      var
        events = ['click', 'blur'],
        textInput = document.querySelector('#textInput');
      // Define functions
      var
        getPrice = function(textInputRef) {
          console.log('__getPrice__', textInputRef.value == '' ? 'Empty' : textInputRef.value);
        },
        getDesc = function(textInputRef) {
          console.log('__getDesc__', 'Description');
        };
      events.forEach(function(e) {
        textInput.addEventListener(e, function() {
          console.log('__EVENT__', e);
          getPrice(this);
          getDesc(this);
        }, false);
      });
    })();
  </script>
</body>
</html>

为了更好地控制Events,最好将事件分别附加到目标元素。

只是个建议!不要在HTML中编写内联JavaScript。出于以下原因,最好单独编写JavaScript(最好是在单独的文件中)。

  1. 减小HTML文件大小
  2. 支持缓存
  3. 提高可访问性
  4. 易于代码维护

希望它能有所帮助!