简体   繁体   English

JavaScript onclick事件问题

[英]JavaScript onclick Event Problem

Let me start off by saying my JavaScript skills are lacking, to say the least. 首先,我要说至少我的JavaScript技能缺乏。 I have been having a problem with the following function: 我一直对以下功能有疑问:

function setClickHandler(element) {
    element.onchange = function () {
        var id = this.options[this.selectedIndex].value;
        if(document.getElementById(id) !== null){
            clickHandler = document.getElementById(id).onclick;
        } else {
            clickHandler ="runMe('" + this.id + "','" + id + "','','null')"; }
        clickHandler.apply(this);
    }
}

Basically what it does is if a element exists with the "id" then use that elements onclick function and if it doesn't exist then create the one within the function. 基本上,它的作用是如果元素带有“ id”,则使用该元素的onclick函数;如果不存在,则在函数中创建一个元素。 Then apply this onclick function to the element. 然后将此onclick函数应用于元素。

Everything works except if the "id" does not exist and it goes into the else statement where the clickHandler has to be created. 一切工作正常,除非“ id”不存在,并且进入必须创建clickHandler的else语句。 I cannot figure out why this won't work. 我不知道为什么这行不通。 I did notice when I logged it if clickHandler was taken from another existing id then clickHandler outputted something like (onclick).event where if it went into the else statement it outputted runMe('24','54','','null'). 我确实在登录时注意到,如果clickHandler是从另一个现有ID中获取的,则clickHandler输出了类似(onclick).event的内容,如果它进入else语句,则输出runMe('24','54','','null “)。

I hope I am explaining this well enough. 我希望我已经解释得足够好了。 Any help would be greatly appreciated, thanks! 任何帮助将不胜感激,谢谢!

you're creating a string in the else case, which you can't call as a function. 在其他情况下,您将创建一个字符串,该字符串不能作为函数调用。 try this 尝试这个

if (document.getElementById(id) !== null) {
    clickHandler = document.getElementById(id).onclick;
    clickHandler.apply(this);
}
else {
    // clickHandler = "runMe('" + this.id + "','" + id + "','','null')";
    var runMeArgs = [this.id, id, '', 'null'];
    runMe.apply(this, runMeArgs);
}

In one case you're setting clickHandler to a function, in the other case you're setting it to a string? 在一种情况下,您将clickHandler设置为一个函数,在另一种情况下,您将其设置为字符串?

if (...) {
   ...
} else {
   var me = this;
   clickHandler = function() {
      runMe(me.id, id, '', null);
   }
}
...

Possibly. 有可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM