手動觸發dom節點事件代碼

来源:http://www.cnblogs.com/rainbow57/archive/2016/01/07/5110128.html
-Advertisement-
Play Games

在爬代碼過程中,碰到一個稀奇古怪的問題。需要手工修改select的值,然後手動觸發select的change事件,但使用網路上查到的通過trigger、onchange()事件觸發都不執行,沒辦法,只好繼續查找。 還好在stackoverflow網站上看到國外大神的回答,解決了碰到的問題。 原帖地址...


在爬代碼過程中,碰到一個稀奇古怪的問題。需要手工修改select的值,然後手動觸發select的change事件,但使用網路上查到的通過trigger、onchange()事件觸發都不執行,沒辦法,只好繼續查找。

還好在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");
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 查看效果:http://hovertree.com/texiao/hoverclock/demo4.htm本插件使用方便,可以在博客園的頁面中使用,請看本頁面右側:http://www.cnblogs.com/roucheng/p/css3clock.html簡潔代碼如下:效果圖圖下:完整代碼如下:...
  • /** * Created by laixi on 2016/1/7. * Date對象擴展 */(function() { // 求當前日期與傳入的日期相隔多少天 if (typeof Date.prototype.getDateInterval != "function") { ...
  • 一、 css 選擇器1.css派生選擇器The strongly emphasized word in this paragraph isred.This subhead is also red.The strongly emphasized word in this subhead isblue....
  • 最近看視頻學習了前端自動化的一些知識,確實讓我大開眼界。感覺前端越來越神器了。同時跟著視頻自己也嘗試運用了一些工具去構建前端項目,但是中間遇見了很多坑,磕磕絆絆的才實現了一點功能,所以打算記錄一下學習過程中的筆記。首先列舉一下關鍵詞:NodeJS、Git、Yeoman、bower、Grunt。 其中...
  • /** * Created by laixiangran on 2015/12/12. * String擴展 */(function() { // 十六進位顏色值的正則表達式 var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; // RG...
  • /** * Created by laixiangran on 2016/01/07. * Array擴展 */(function() { // 遍曆數組 if (typeof Array.prototype.forEach != "function") { Array.p...
  • JQM 日期插件 mobiscroll Demo
  • 對於字元串的切割截取平時所用可能不是特別多,而且分的比較細,所以自備自查。有備無患。由於之前所有均在一個demo測試,若是哪裡打錯了,敬請諒解。一些其餘屬性找時間繼續添加。1.函數:split()功能:使用一個指定的分隔符把一個字元串分割存儲到數組例子: str=”jpg|bmp|gif|ico|p...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...