绑定JavaScript's oninput事件的最佳jQuery插件实现

Best jQuery plugin implementation for binding JavaScript's oninput event

本文关键字:最佳 jQuery 插件 实现 事件 oninput JavaScript 绑定      更新时间:2023-09-26

我知道jQuery不支持oninput事件,所以我自己开始写一个插件来做这项工作。虽然我不太了解jQuery或JavaScript中与事件相关的所有东西,但我最终得到了可用的代码,目前满足了我的要求。

不幸的是,我认为我目前的实现可能会崩溃,特别是当它与其他库一起使用时,因为我直接设置了DOM元素的oninput成员。

你知道一个更好的和可移植的方法来解决这个问题,也许使用方法,如jQuery的"on"或JavaScript的"addEventListener"?

这是我目前使用的代码的一个工作示例:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
////////////////////////////////////////////////////////////////////////////
// jQuery plugin to bind an event handler to the "oninput" JavaScript event.
(function ($) {
   // Add an "input" method to all jQuery objects
   $.fn.input = function (handler) {
      // iterate over all DOM elements in the jQuery object
      this.each( function () {
         // set a new method to run when "oninput" is fired
         this.oninput = function (prevHandler) {
            return function (ev) {
               // call previous handler if exists
               if( typeof prevHandler === 'function' ) {
                  prevHandler.call (this, ev);
               }
               // call new handler
               handler.call (this, ev);
            };
         }(this.oninput);  // immediate evaluation, pass current handler as argument
      });
   };
} (jQuery));
////////////////////////////////////////////////////////////////////////////
</script>
<script type="text/javascript">
// Test the plugin
$(document).ready (function () {
   $('#one').input (function () {
      alert ('Input on one: ' + $(this).val());
   });
   $('#three,#four').input (function () {
      alert ('Input on three or four: ' + $(this).val());
   });
   $('#one,#two,#three').input (function () {
      alert ('Input on one, two, or three: ' + $(this).val());
   });
   $('#one,#two,#three,#four').input (function () {
      alert ('Input on any: ' + $(this).val());
   });
});
</script>
</head>
<body>
<input id='one'/><br/>
<input id='two'/><br/>
<input id='three'/><br/>
<input id='four'/><br/>
</body>
</html>

提前感谢!!

jQuery的'on'可以处理任何事件,所以你可以简单地做这样的事情:

(function() {
    var outputElement = document.getElementById('mirror-input');
    $('#input-stuff').on('input', function (event) {
        outputElement.innerText = event.target.value; 
    });
}())
http://jsfiddle.net/YCAtZ/