如何从函数func()获取面值并将其用于附加到另一个函数中的a_span元素handlerFunction()
。par是一个ID。在handlerFunction()
,我需要得到a_spanID
。
例如:
document.getElementById('a_span35')
function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = handlerFunction();
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name="+par);
}
function handlerFunction() {
if (XMLHttp.readyState == 4) {
document.getElementById('a_span').innerHTML=XMLHttp.responseText;
}
}
最简单的方法就是把handlerFunction
里面 func
,所以它关闭了par
(但我下面给你一个选择):
function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = handlerFunction;
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name=" + par);
function handlerFunction() {
// You can use `par` here, even though `func` has already returned
if (XMLHttp.readyState == 4) {
document.getElementById('a_span').innerHTML = XMLHttp.responseText;
}
}
}
该handlerFunction
是一个封闭在调用的上下文func
。不用担心这个词,闭包并不复杂。
另请注意,您在上面我已更正的代码中有一个错误:
XMLHttp.onreadystatechange = handlerFunction();
...,它会立即调用 handlerFunction
并将其返回值分配给onreadystatechange
(正是x = foo();
调用 foo
并将返回值分配给的方式x
)。它应该是:
XMLHttp.onreadystatechange = handlerFunction;
我假设您正在创建某处XMLHttp
(并且我建议为每次调用都创建一个新的func
,而不是重复使用)。
替代方案:
您可以handlerFunction
通过将调用包装在另一个函数中来保持分离,方法是手动进行:
function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = function() {
handlerFunction(XMLHttp, par);
};
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name=" + par);
}
function handlerFunction(xhr, par) {
if (xhr.readyState == 4) {
// use par
document.getElementById('a_span').innerHTML = xhr.responseText;
}
}
...或使用ES5 Function#bind
:
function func(par) {
XMLHttp.open("POST", "some.php");
XMLHttp.onreadystatechange = handlerFunction.bind(undefined, XMLHttp, par);
XMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
XMLHttp.send("post_name=" + par);
}
function handlerFunction(xhr, par) {
if (xhr.readyState == 4) {
// use par
document.getElementById('a_span').innerHTML = xhr.responseText;
}
}
您需要Function#bind
在没有本地功能的浏览器中使用填充程序。所要做的bind
是返回一个函数,该函数在被调用时调用具有给定this
值(第一个参数)的原函数以及要提供给定值的参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句