如何使用$(this)访问调用Javascript函数的按钮的id

How to access the id of the button who called a Javascript function using $(this)?

本文关键字:函数 Javascript 按钮 id 调用 访问 何使用 this      更新时间:2023-09-26

我是Javascript新手。我在一个页面上设置了几个按钮,像这样:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout" onclick="loadXMLDoc2()">Logout</button>
</div>
...

我想提取调用loadXMLDoc2()的按钮的id。这个方法定义如下:

function loadXMLDoc2() {
    var retr = $(this).attr("id");
    document.getElementById("L1_LEFT").innerHTML
        = retr;
}

然而,当我点击按钮时,L1_LEFT被设置为undefined。我认为$(this)意味着"当前的HTML元素"。如果不是按钮,那是什么?如何提取按钮的id?

this指的是函数内部的window(全局对象),this指的是onclick处理器中的element

虽然在html中做javascript是不好的方法,试试这个:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout" onclick="loadXMLDoc2(this)">Logout</button>
</div>
function loadXMLDoc2(elm) {
    var retr = elm.id;
    document.getElementById("L1_LEFT").innerHTML
    = retr;
}

更好的方法是将HTML和javascript分开:

<div id='MID_1_4'>
    <div id="login">logout</div>
    <button type="button" id="logout">Logout</button>
</div>

(在js文件的某处)

function loadXMLDoc2(elm) {
    var retr = elm.id;
    document.getElementById("L1_LEFT").innerHTML = retr;
}
$( document ).ready( function(){
//This function is executed after all elements on the page are ready to be manipulated
    $( "#logout" ).bind( "click",
        function(){
        loadXMLDoc2( this );
        }
    );
});

是的,this变量指的是事件处理程序的目标元素。不过,我认为你把它弄得太复杂了。试着

var retr = this.id;

获取您的id。吻! !