gpt4 book ai didi

javascript - 如何将 id 传递给函数?

转载 作者:行者123 更新时间:2023-12-02 15:04:16 25 4
gpt4 key购买 nike

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 的任何其他部分)。

JSFiddle

关于javascript - 如何将 id 传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com