如何将引用“this”从 <a> 标签传递给 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9026697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:25:56  来源:igfitidea点击:

How to pass the reference 'this' to a javascript function from an <a> tag

javascripthtml

提问by DKean

I know that this is elementary, but I'm completely unable to pass "this" as a parameter to a JavaScript function. I'm numb from trying...

我知道这是基本的,但我完全无法将“this”作为参数传递给 JavaScript 函数。我已经麻木了……

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
    function ko(control.id){
    alert(control);
}
</script>

<body>
<div id"lala">
    <a id="la" href="javascript:ko(this)" >Votes & Concerns</a>
</div>

</body>
</html>

The alert tells me "undefined!"

警报告诉我“未定义!”

回答by ori

<a id="la" href="#" onclick="ko(this); return false;" >Votes & Concerns</a>

回答by Pointy

Don't do it from the "href" value, do it from a real event handler attribute:

不要从“href”值开始,从真实的事件处理程序属性开始:

<a id='la' href='#' onclick='ko(event, this)'>

Pass in the eventso that you can prevent the default interpretation of a click on an <a>from being undertaken by the browser.

传入event以便您可以防止<a>浏览器对单击的默认解释。

function ko(event, element) {
  if ('preventDefault' in event) event.preventDefault();
  event.returnValue = false; // for IE

  // here "element" will refer to the clicked-on element ...
}

回答by lonesomeday

You've got it the wrong way round:

你理解错了:

function ko(control){
    alert(control.id);
}

controlis the object (the DOM element object, to be precise) that you're passing with ko(this). You then want to access its idproperty with control.id.

control是您要传递的对象(准确地说是 DOM 元素对象)ko(this)。然后您想id使用control.id.



NB also that there are much better ways of doing this. The best is to assign the event handlers in Javascript blocks rather than in HTML attributes. For instance:

注意还有更好的方法可以做到这一点。最好是在 Javascript 块中而不是在 HTML 属性中分配事件处理程序。例如:

document.getElementById('la').onclick = function() {
    alert(this.id);
};