我无法将通过func传递的事件传递给针对XMLHttpRequest.onreadystatechange
调用的内联函数。将事件从函数func
传递到内联函数时,它表示未定义的值。 PFB的内联注释相同。
event.currentTarget.addEventListener("click", func, false);
function func(event){
var data1;
var str=event.currentTarget.textContent; //here variable value for str is coming successfully.
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(event)
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("event is"+event.currentTarget.textContent); //here event.currentTarget.textContent is coming undefined . Is there a way to get the value here similar to variable str?
data1= xmlhttp.responseText;
}
}
xmlhttp.open("GET","Jr6?q="+str,true); //here simply calling the servlet to get the data which is stored in data1 above.
xmlhttp.send();
}
答案 0 :(得分:0)
请尝试从内部函数中删除“事件”参数,而只需使用var“ str”:
event.currentTarget.addEventListener("click", func, false);
function func(event){
var data1;
var str=event.currentTarget.textContent;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("event is" + str);
data1= xmlhttp.responseText;
}
}
xmlhttp.open("GET","Jr6?q="+str,true);
xmlhttp.send();
}
您可以在此处了解有关闭包的信息:https://www.w3schools.com/js/js_function_closures.asp