事件监听器无法正常工作

时间:2018-03-09 07:41:28

标签: javascript jsp

我试图将onClick事件监听器注册到每个动态创建的img元素。当我试图将参数传递给eventHandler函数时,事件被激活或者在页面加载时调用处理函数,并且在此之后它不起作用但是当我不将参数传递给事件处理函数时它工作正常

request.onreadystatechange = function() {
            try {
                if (this.response.contentlength != 0) {
                    var urlCreator = window.URL || window.webkitURL;
                    var imageUrl = urlCreator
                            .createObjectURL(this.response);
                    var elem = document.createElement("img");
                    elem.setAttribute("style","width:100%");
                    elem.setAttribute("src", imageUrl);
                    elem.addEventListener("click",on);
                // here elem.addEventListener("click",on(elem));
                    parent.appendChild(elem);
                }
            } catch (Exception) {
            }
        };
        request.send();
    }

    //for overlay effect
    //function on(ele){
    function on(){  
        document.getElementById("overlay").style.display="block";   
    }

2 个答案:

答案 0 :(得分:0)



request.onreadystatechange = function() {
            try {
                if (this.response.contentlength != 0) {
                    var urlCreator = window.URL ||        window.webkitURL;
                    var imageUrl = urlCreator
                            .createObjectURL(this.response);
                    var elem = document.createElement("img");
                    elem.setAttribute("style","width:100%");
                    elem.setAttribute("src", imageUrl);
                    //
                    elem.addEventListener("click",on);
                // here elem.addEventListener("click",on(elem));
                    parent.appendChild(elem);
                }
            } catch (Exception) {
            }
        };
        request.send();
    }

    //for overlay effect
    //function on(ele){
    // the listener function always takes event as first parameter and event has the information about from which element this listener is called
    function on(evt){  
        var targ = evt.target || evt.srcElement;
        document.getElementById("overlay").style.display="block";   
    }




答案 1 :(得分:0)

//或者,如果你想传递参数..请参考下面的代码



@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if(keyCode!=KeyEvent.KEYCODE_BACK)return false;

    //enter the required code here to go to the necessary activity
    return true;
}