JS腳本實(shí)現(xiàn)動(dòng)態(tài)給標(biāo)簽控件添加事件的方法

字號(hào):


    本文實(shí)例講述了JS腳本實(shí)現(xiàn)動(dòng)態(tài)給標(biāo)簽控件添加事件的方法。分享給大家供大家參考,具體如下:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <script language="javascript">
    function set()
    {
    var obj = document.getElementById("fy");
    //obj.attachEvent('onfocus', add); //在原先事件上添加
    //obj.setAttribute('onfocus',add); //會(huì)替代原有事件方法
    //obj.onfocus=add;
    //等效obj.setAttribute('onfocus',add);
    if(window.addEventListener)
    {
    //其它瀏覽器的事件代碼: Mozilla, Netscape, Firefox
    //添加的事件的順序即執(zhí)行順序
    //注意用addEventListener 添加帶on的事件,不用加on
    obj.addEventListener('focus', add, false);
    }
    else
    {
    //IE 的事件代碼 在原先事件上添加 add 方法
    obj.attachEvent('onfocus',add);
    }
    }
    function add(){alert("已經(jīng)成功添加事件");}
    </script>
    <body>
    <input type="text" onfocus="alert('預(yù)設(shè)事件');" id="fy" />
    <input type="button" onclick="set();" value="sssss"/>
    </body>
    </html>
    PS:代碼排版貌似不太盡如人意,這里小編給大家推薦幾款代碼格式化工具,相信在以后的編程開發(fā)中能夠用得到:
    C語(yǔ)言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
    http://tools.jb51.net/code/ccode_html_css_json
    在線JavaScript代碼美化、格式化工具:
    http://tools.jb51.net/code/js
    JavaScript代碼美化/壓縮/格式化/加密工具:
    http://tools.jb51.net/code/jscompress
    在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
    http://tools.jb51.net/code/json
    json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
    http://tools.jb51.net/code/jsoncodeformat
    希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。