手动触发dom节点事件代码
2016-01-07 15:49
501 查看
在爬代码过程中,碰到一个稀奇古怪的问题。需要手工修改select的值,然后手动触发select的change事件,但使用网络上查到的通过trigger、onchange()事件触发都不执行,没办法,只好继续查找。
还好在stackoverflow网站上看到国外大神的回答,解决了碰到的问题。
原帖地址:http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
手工触发的代码如下:还好在stackoverflow网站上看到国外大神的回答,解决了碰到的问题。
原帖地址:http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript
/** * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically * by testing for a 'synthetic=true' property on the event object * @param {HTMLNode} node The node to fire the event handler on. * @param {String} eventName The name of the event without the "on" (e.g., "focus") */ function fireEvent(node, eventName) { // Make sure we use the ownerDocument from the provided node to avoid cross-window problems var doc; if (node.ownerDocument) { doc = node.ownerDocument; } else if (node.nodeType == 9){ // the node may be the document itself, nodeType 9 = DOCUMENT_NODE doc = node; } else { throw new Error("Invalid node passed to fireEvent: " + node.id); } if (node.dispatchEvent) { // Gecko-style approach (now the standard) takes more work var eventClass = ""; // Different events have different event classes. // If this switch statement can't map an eventName to an eventClass, // the event firing is going to fail. switch (eventName) { case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead. case "mousedown": case "mouseup": eventClass = "MouseEvents"; break; case "focus": case "change": case "blur": case "select": eventClass = "HTMLEvents"; break; default: throw "fireEvent: Couldn't find an event class for event '" + eventName + "'."; break; } var event = doc.createEvent(eventClass); var bubbles = eventName == "change" ? false : true; event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable. event.synthetic = true; // allow detection of synthetic events node.dispatchEvent(event, true); } else if (node.fireEvent) { // IE-old school style var event = doc.createEventObject(); event.synthetic = true; // allow detection of synthetic events node.fireEvent("on" + eventName, event); } };
html代码和调用如下
<a href="http://www.google.com" onclick="alert('clicked')" target="_blank">Go to google</a> <button>Trigger event</button> document.getElementsByTagName("button")[0].onclick = function() { fireEvent(document.getElementsByTagName("a")[0], "click"); }
相关文章推荐
- Python发送邮件
- 笨方法学Python(46-50)
- [Leetcode]@python 62. Unique Paths
- 2016/1/7文件上传下载代码
- C# 两个独立exe程序直接通信
- Java基础之基本类型转换知识点详解
- noetpad++ 使用svn
- Ubuntu 14.04 安装JDK 配置环境变量
- 绘图技术、事件监听 Java
- Go语言编程入门超级指南
- Spring MVC 学习笔记(二)
- 【第六章】 AOP 之 6.4 基于@AspectJ的AOP ——跟我学spring3
- Java基础之数据类型简摘
- Eclipse对工作空间中的项目进行分组
- eclipse,android studio工具疑惑
- JAVA发送邮件代码
- java Enumeration用法
- spring security+extjs session超时解决方案 博客分类: 软件架构
- java入门第二季.笔记
- C语言用igraph读取GML文件