未捕获的TypeError:无法读取属性' addEventListener'在chrome浏览器中为null

时间:2015-05-21 12:17:29

标签: javascript google-chrome

**While running apps in chrome browser I'm getting
    `Uncaught TypeError: Cannot read property 'addEventListener' of null` but in IE it is working fine.
    I this line m getting issues"   if (elem.addEventListener)   "
    if (elem.addEventListener)
    elem -->myForm
    elem is parameter replaced by myForm variable.

我添加了javascript代码以及HTML代码。     请解释以下代码的解决方案。**

    function addEvent(elem, event, fn) {
    function listenHandler(e) {
    var ret = fn.apply(this, arguments);
    if (ret === false) {
    e.stopPropagation();
    e.preventDefault();
    }
    return(ret);
    }

    function attachHandler() {
    var ret = fn.call(elem, window.event);   
    if (ret === false) {
    window.event.returnValue = false;
    window.event.cancelBubble = true;
    }
    return(ret);
    }

    if (elem.addEventListener) {**here is issue**
    elem.addEventListener(event, listenHandler, false);
    } else {
    elem.attachEvent("on" + event, attachHandler);
    }
    }

    var myForm = document.getElementById("1form");

    addEvent( myForm, 'submit', function() { return validateForm(document.nextForm, document.1form); } ); 

以下是我认为可以提供帮助的HTML代码,如果有任何需要请让我知道.HTML代码包含java代码,你可以看到<%和%>这里我插入java代码

<html >
<script language="javascript"></script>
<%   java code%>
<body ><table >
//
</table>

<form action="someAction" method="post"
onsubmit="javascript:return validateForm(document.someForm)"  >

</form>

<% 
java code
if (condition ) {%>
<form name="1form" target="1target"  >
<% 
} else {
%>
<form name="1form"    target="2target"  >
<% }%>
</form>

</body>    
<script>
function addEvent(elem, event, fn) {
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}

function attachHandler() {
var ret = fn.call(elem, window.event);   
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}

if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}    

var myForm = document.getElementById("prsregistrationform");

</script>
</html>

0 个答案:

没有答案