如何将 id 传递给函数

How to pass id to a function?

本文关键字:函数 id      更新时间:2023-09-26

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。我该怎么做?

问题是function 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