`

javascript - trick to simulate the change event

阅读更多

 

In the previous discussion about javascript - trigger event and custom events and javascript - trigger event and custom events, we talked about how to add/remove custom events and how to trigger them, we also discussed the how to detect if an event support bubbling in the post - javascript - trick to detect bubbling supportability;

 

 

This topic will address another one of the event that does not bubble. In IE, the change event does not bubble neither, to simulate a change event, it is a bit complicated, but it is still possible.  

 

/**************************************
*@Name: change.js
*  simulate a change event in IE that has the bubbling ability
*@Summary
* the keys to the change event are
*   1. focusout to check out the value after moving away from the form element
*   2. the click and keydown event for checking the value instant it's changed
*   3. beforeactivate for getting the previous value before a new one is set
*@NOTE:
*   to use this event, you will need the following dependencies.
*     1. addremoveevents.js
*     2. isEventSupported.js
* @Usage
*    
* @todo:
*   Test
***************************************/
(function () {
  // we want to simulate change events on these elements
  var formElements = /textarea|input|select/i;

  // check to see if the submit event works as we expect it to 
  if (!isEventSupported("change"))  {
    this.addChange = function(elem, fn) { 
      addEvent(elem, "change", fn);

      // only add the handler for the first handler bound
      if (getData(elem).events.change.length === 1) {
        addEvent(elem, "focusout", testChange);
        addEvent(elem, "click", changeClick);
        addEvent(elem, "keydown", changeKeydown);
        addEvent(elem, "beforceactivate", changeBefore);
      }
    };

    this.removeChange = function(elem, fn) { 
      removeEvent(elem, "change", fn);
      var data = getData(elem);

      // only remove the handlers when there's 
      // nothing left to remove
      if (!data || !data.events || !data.events.submit) { 
        removeEvent(elem, "focusout", testChange);
        removeEvent(elem, "click", changeClick);
        removeEvent(elem, "keydown", changeKeydown);
        removeEvent(elem, "beforceactivate", changeBefore);
      }
    };
  }
  else {
    this.addChange = function(elem, fn) { 
      addEvent(elem, "change", fn);
    };
    this.removeChange = function(elem, fn) { 
      removeEvent(elem, "change", fn);
    };
  }

  function changeClick(e)  {
    var elem = e.target, type = elem.type;

    if (type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select") { 
      return testChange.call(this, e);
    }
  }

  // Change has to be called before submit
  // Keydown will be called before keypress,
  // which is used in submit-event delegation
  function changeKeydown(e) { 
    var elem = e.target, type = elem.tpye, key = e.keyCode;


    if (key === 13 && elem.nodeName.toLowerCase() !== "textarea" || key === 32 || (type === "checkbox" || type === "radio") ||
        type === "select-multiple") {
        return testChange.call(this, e);
    }
  }

  // Beforeactivate happens before the previous element is blurred
  // Use it to store information for later checking
  function changeBefore(e) {
    var elem = e.target;
    getData(elme)._change_data =  getVal(elem); // this is to sotre hte before change data it to some location
  }

  // Get a string value back for a form element
  // that we can use to verify if a change has occurred
  function getVal(elem) {
    var type = e.type, val = elem.value;

    // checkboxes and radios only change the checkied state
    if (type === "radio" || type === "checkbox") { 
      val =  elem.checked;
    } else if (type  === "select-multiple") { 
      val = "";
      if (elem.selectedIndex > -1) {  
         for (var i = 0; i < elem.options.length; i++) { 
           val += "-" + elem.options[i].selected;
         }
      }
    }
   // Regular selects only need to check what
   // option is currently selected
   else if (elem.nodeName.toLowerCase() ==== "select") { 
     val = elem.selectedIndex;
   }
   return val;
  }
  // Check to see if a change in the value has occurred
  function testChange(e) {
    var elem = e.target, data, val;

    // Don't need to check on certain elements and read-only inputs
    if (!formElems.test(elem.nodeName) || elem.readOnly) { 
      return;
    }

    // Get the previously-set value
    data = getData( elem )._change_data;
    val = getVal(elem);

    // the current data will be also retrieved by beforeactivate
    if (e.type !== "focusout" || elem.type !== "radio") { 
      getData(elem)._change_data = vall;
    }

    // if there's been no change than we can bail
    if (data === undefine || val === data)  {
      return ;
    }
    // Otherwise the change event should be fired
    if (data!= null || val) {
      return triggerEvent(elem, "change");
    }
  }
})();
 
分享到:
评论

相关推荐

    Pandas-and-NumPy-Tips-Trick-and-Techniques-master.zip

    Pandas-and-NumPy-Tips-Trick-and-Techniques-master

    S-a-D-trick.rar_Join In

    在VB6(Visual Basic 6)中,"S-a-D-trick.rar_Join In" 这个主题涉及到的是文件分割与合并的技术。在处理大文件时,为了方便传输或者存储,我们可能会选择将其分割成多个小文件,而在需要使用整个文件时,则需要将...

    python-trick

    Python-trick,上传的事pdf文档

    在规定的时间内,使用鼠标控制帽子接住落下的保龄球,躲避炸弹。_Hat-Trick.zip

    在规定的时间内,使用鼠标控制帽子接住落下的保龄球,躲避炸弹。_Hat-Trick

    HLP-Trick-crx插件

    【HLP-Trick-crx插件】是一款专为解决特定网页限制而设计的浏览器扩展程序,主要用于恢复用户在浏览网页时被禁用的复制、粘贴功能,以及上下文菜单和本地高亮显示功能。这款插件特别适用于那些因为版权保护或者安全...

    深度学习领域CNN橄榄球比赛NFL目标检测(带数据集)-cnn-baseline-more-tta-trick

    语言:python 内容包括:源码、数据集、数据集描述、论文 目的:使用CNN算法在橄榄球比赛中目标检测。 带数据集很好运行,主页有搭建环境过程。主页有更多源码。 数据集描述如下: 在这场比赛中,你的任务是预测球员...

    gtg-grind-trick-generator

    gtg-grind-trick-generator PWA Web应用程序(Node.js,JS,HTML,CSS) Chrome,Safari,Firefox,Edge(Android,iOS,MacOS,Windows) 离线工作Android应用程式使用Google Workbox,Webpack制作

    py-trick-book:关于 Python 的高级提示和技巧

    Python 提示和技巧 ... git clone https://github.com/plasmashadow/py-trick-book.git 我假设您安装了 ipython 导航到目录并执行 ipython notebook 笔记: 退出间谍活动并自己阅读 或者 保持冷静,加入草帽海贼团

    21-card-trick:在 React 中完成的 21 张卡片技巧

    React 21 卡技巧一个演示卡片技巧的React应用程序。动机该项目旨在学习如何使用 React 钩子和进行嵌套的 api 调用。 该项目不再进行。怎么玩记住 21 张卡片中的 1 张后,单击完成。 选择您的卡片所在的 3 堆中的哪一...

    tips-n-trick

    ...DOCTYPE&gt;声明、元素、元素和元素。&lt;!...包含元数据,如标题()、字符集(&lt;meta charset="UTF-8"&gt;)和链接外部资源(如CSS文件)。则包含网页的可见内容,如文本、图像、链接等。...例如,使用和来定义页面头部和底部,...

    [Head.First.JavaScript].Michael.Morrison...

    Use the [removed] tag to tell the browser you’re writing JavaScript 11 Your web browser can handle HTML, CSS, AND JavaScript 12 Man’s virtual best friend... needs YOUR help 15 Making iRock ...

    vdr-hattrick-开源

    1. 下载最新版本的源代码,例如压缩包内的hattrick-0.1.6。 2. 在VDR环境中编译和安装插件。这可能需要熟悉Linux环境和基本的编译命令。 3. 配置VDR以启用Hattrick插件,并设置与Hattrick账户的连接信息。 4. 更新...

    计算机网络第六版答案

    For example, she can easily change the phrase “Alice, I owe you $1000” to “Alice, I owe you $10,000”. Furthermore, Trudy can even drop the packets that are being sent by Bob to Alice (and vise-...

    CMCC-Trick:招惹CMCC-* WLAN

    Trick-CMCC 利用CMCC公共热点的小漏洞免费上网~~ :) sudo ./conn.sh Notice: 目前只知道我工CMCC有这特色, 其他地区尚不明确 Notice: 脚本适用于使用NetWorkManager网络sds管理工具的系统 Notice: 不必惊讶原理, ...

    The Kernel Trick.pdf

    在机器学习中,核技巧(Kernel Trick)是一种非常重要的技术,它允许我们在高维特征空间中有效地进行线性学习算法的操作,而无需显式地计算出高维空间的数据表示。核技巧在诸如支持向量机(SVM)等算法中发挥了重要...

    HLP-绝招「HLP-Trick」-crx插件

    该扩展程序重新启用网页上的复制/粘贴功能,上下文菜单和本机突出显示功能。 支持语言:English (United States)

    Hat_Trick_The Catch Game.unitypackage

    Hat Trick是Unity官方商店提供的5.5.0版本以上的一款游戏Demo。

    The Manual of Mathematical Magic(数学魔术手册)

    language we use to describe the world around us - it’s the basis of all the sciences. This book will show you how to perform some magical miracles to impress and entertain your friends. But it ...

    Trick

    "Trick"这一主题似乎与一套特别的字体资源相关,其中包括多种不同风格的图像文件(.gif)和TrueType字体文件(.TTF)。让我们深入探讨一下这个话题。 首先,.gif 文件是一种常见的图像格式,支持透明度和动画,常...

    Pro Silverlight2 in CSharp 2008

    If this all sounds eerily familiar, it’s because the same trick has been tried before. Several other technologies use a plug-in to stretch the bounds of the browser, including Java, ActiveX, ...

Global site tag (gtag.js) - Google Analytics