JavaScript自定義事件,動態添加屬性


根據事件的不同,可用的自定義方法也不同。

document.createEvent('Event');

 

實現主要有4個步驟:

1.創建事件。

2.初始化事件(三個參數:事件名,是否起泡,是否取消默認觸發)

3.監聽事件

4.觸發事件

 var Evt = document.createEvent('Event');//創建一個事件
 Evt.initEvent('inputChangeEvt', true, true);//初始化事件,給定事件名字
window.addEventListener('Evt', function (event) {//監聽這個自定義事件動沒動
        console.log(event);
    });
window.dispatchEvent(Evt);//觸發自定義inputChangeEvt事件

具體實現。

<!DOCTYPE html>
<html>
<head>
    <meta charset=utf-8" />
    <title>By:DragonDean</title>
    <script type="application/javascript">
        window.onload=function(){
            var evt=document.createEvent('Event');
            evt.initEvent('myEvent',true,true);
            var obj=document.getElementById('testBox');
            obj.addEventListener('myEvent', function(){
                console.log('myEvent 事件觸發了');
            }, false);
            obj.dispatchEvent(evt);
        };
    </script></head>
<body>
<div id="testBox">ddddd</div>
</body>
</html>

當然,自定義事件是的場景肯定不是這么簡單,工作中剛好需要做一個自定義事件,用於我如果發生數據改變,就將數據發送給其它js。其中牽扯到動態添加屬性,事件傳值等。

/**
 * Created by v_zweiwang on 2015/10/26.
 */
window.onload = function () {
    window.addEventListener('inputChange', function (event) {//監聽這個自定義事件動沒動
        console.log(event.detail);
    });
    myBord.init();//使用
};
(function(){
    window['myBord'] = {};
    function init() {
        myBord.inputChangeEvt = document.createEvent('Event');//創建一個事件
        myBord.inputChangeEvt.initEvent('inputChange', true, true);//初始化事件,給定事件名字
        //初始化一下數據
        myBord.inputChangeEvt.detail = {
            TranslateX: '0.00',
            TranslateY: '0.00',
            TranslateZ: '0.00',
            RotateX: '0.00',
            RotateY: '0.00',
            RotateZ: '0.00',
            Scale: '1.00'
        };
        try {
            window.dispatchEvent(myBord.inputChangeEvt);//觸發自定義inputChangeEvt事件
        } catch (e) {
            console.error(e);
        }
    }
    window['myBord']['init'] = init;
})();

至此,已經可以利用事件傳值了。直接將以上代碼復制到html中,運行,鍵盤F12,就能看到以下輸出。

好,現在來講講實現。

(解釋代碼)

如何動態添加屬性。

如何利用事件傳遞值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM