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:
<img id="1210" onclick="executeOnclick()" onload="myElement(this);"
class="Cpictures" src="1.jpg" width=50px height=75px alt="Robert" />
该代码不起作用。我希望当我调用 myFunction 函数时,我可以获得图像的 ID 并将其传递给我的 API。我该怎么做?
最佳答案
问题是函数 myElement()
不接受任何参数。传递 this
会传递调用它的对象的引用(具体来说,在本例中是 HTMLImageElement
的实例)。但你的函数根本不寻找任何东西。
更改您的功能:
function myElement(){
var getID = document.getElementById(this.id);
}
至:
function myElement(obj){
//Insert code you want here. I printed the id to console for example.
console.log(obj.id);
}
将允许您访问对象的 id(以及您想要使用的 id 的任何其他部分)。
关于javascript - 如何将 id 传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215545/