javascript 尝试以内部方法为目标时出现范围问题

javascript scope issue when trying to target an inside method

我有一个 js 文件,代码如下:

var myAnonFun = function (param1) {


function createHTML(){

.....
sHTML += "<select id=param1 onchange='makeCalculations(this)'  >";
}

var vText = document.getElementById("results");
vText.innerHTML = sHTML;


function makeCalculations(){
}

}

然后,在 HTML 文件中,我有这样的内容:

var createAnonFun = myAnonFun (param1);

js 文件中的代码将按预期运行。但是,每当在 js 文件中创建的 select html 对象中更改值时,我将收到一条错误消息,指出没有 makeCalculations 函数。

据我了解,问题是 select 对象正试图从全局范围访问一个函数,当然那里没有。

所以我的问题是:如何将 select 对象定位到 myAnonFun 变量中的 makeCalculations 函数?

提前致谢!

makeCalculationsvar myAnonFun = function (param1) { 中声明,因此它的作用域是该函数的局部范围(它不能全局访问)。

你最好的选择是,不要声明内联事件处理程序,而是使用事件侦听器:

所以代替:

sHTML += "<select id=param1 onchange='makeCalculations(this)'  >";

做:

sHTML += "<select id=param1>";

vText.innerHTML = sHTML; // Without this the following event listener will not work

// and when you are sure the <select> above has been added to the DOM
document.getElementById('param1').addEventListener('change', function() {
    makeCalculations(document.getElementById('param1'));
});


另一种选择(虽然不推荐)是使 makeCalculations 全局可用:

变化:

sHTML += "<select id=param1 onchange='makeCalculations(this)'  >";

至:

sHTML += "<select id=param1 onchange='createAnonFun.makeCalculations(this)'  >";

最后:

    function makeCalculations(){
    ...
    }
}

至:

    function makeCalculations(){
    ...
    }
    return {makeCalculations};
}

请注意,要使其正常工作,您必须在某处执行(在函数之外):

var createAnonFun = myAnonFun (param1);

您可以使 makeCalculations 在全局范围内可用:

this.makeCalculations = function() {
  // ....
}

// Outside:

myAnonFun.makeCalculations();

而不是sHTML += "<select id=param1 onchange='makeCalculations(this)' >";

您可以使用以下内容。

var selectElement = document.createElement("select");
selectElement.addEventListener("change", makeCalculations);
vText.appendChild(selectElement); //this or replace all contents of vText

此方法还消除了不必要的字符串连接混淆。