Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将id传递给函数?_Javascript_Ajax_Api - Fatal编程技术网

Javascript 如何将id传递给函数?

Javascript 如何将id传递给函数?,javascript,ajax,api,Javascript,Ajax,Api,JavaScript: function executeOnclick() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { myFunction(xhttp); } }; xhttp.

JavaScript:

function executeOnclick() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) { 
            myFunction(xhttp);
        }
    };

    xhttp.open("GET","http://try.com/students/search.php?stud_id=?" +x , true);
    xhttp.send();
}   

function myFunction(obj){
    var xmlDoc = obj.responseText;
    var x = xmlDoc.getElementsByTagName("id");

    document.getElementById("demo").innerHTML = xhttp.responseText;
}   
HTML:



这个代码不起作用。我希望在调用myFunction函数时,获取图像的Id并将其传递给API。怎么做?

问题是
函数myElement()
不接受任何参数。传递
this
传递调用它的对象的引用(具体来说,在本例中是
HTMLImageElement
的实例)。但您的函数根本不需要任何东西

将您的功能更改为:

function myElement(){
    var getID = document.getElementById(this.id);
}   
致:

将允许您访问对象的id(以及要使用的id的任何其他部分)


问题在于
函数myElement()
不接受任何参数。传递
this
传递调用它的对象的引用(具体来说,在本例中是
HTMLImageElement
的实例)。但您的函数根本不需要任何东西

将您的功能更改为:

function myElement(){
    var getID = document.getElementById(this.id);
}   
致:

将允许您访问对象的id(以及要使用的id的任何其他部分)


使用“this”作为函数参数名可能不是最好的主意-事实上,它根本不起作用id应该是
this.id
而不是
“this.id”
我编辑了我的代码,你能检查一下这是否是你的意思吗?还有,为什么传递“this”无效?您的函数
myElement
如何获得对
this
的引用?不太
函数myElement(x){var getID=document.getElementById(x.id);}
应该这样做使用“this”作为函数参数名可能不是最好的主意-事实上,它根本不起作用id应该是
this.id
而不是
“this.id”
我编辑了我的代码,你能检查一下这是否是你的意思吗?还有,为什么传递“this”无效?您的函数
myElement
如何获得对
this
的引用?不太<代码>函数myElement(x){var getID=document.getElementById(x.id);}应该可以完成它,它可以完美地工作。但是我遇到了麻烦,因为它会在我点击图片之前提醒我对象id。然后删除该提醒,并放入任何你想要的代码。我的意思是作为一个示例,而不是作为一个可复制的解决方案。@SatejS抱歉,没有扩展注释以查看您的注释。对此表示抱歉。我编辑了我的代码,我是否以这种方式传递从myElement函数中获得的元素?它工作得非常好。但是我遇到了麻烦,因为它会在我点击图片之前提醒我对象id。然后删除该提醒,并放入任何你想要的代码。我的意思是作为一个示例,而不是作为一个可复制的解决方案。@SatejS抱歉,没有扩展注释以查看您的注释。对此表示抱歉。我编辑了我的代码,我是否以这种方式传递从myElement函数获得的元素?
function myElement(obj){
    //Insert code you want here. I printed the id to console for example.
    console.log(obj.id);
}