Javascript 获取函数中点击元素的 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2952767/
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-23 02:39:04  来源:igfitidea点击:

Get ID of clicked on element in function

javascriptjquery

提问by skerit

I want to get the ID of an element I click on. I put the function in the onclick element, like this:

我想获取我单击的元素的 ID。我将函数放在 onclick 元素中,如下所示:

<a id="myid" class="first active" onclick="markActiveLink();" href="#home">Home</a>

And this is in the function:

这是在函数中:

function markActiveLink() {   
    alert($(this).attr("id"));
}

This doesn't work, as it says it isn't defined. Does it really forget about the ID, do I have to type it in the onclick?

这不起作用,因为它说它没有定义。它真的忘记了 ID,我必须在 onclick 中输入它吗?

回答by No Surprises

Try: onclick="markActiveLink(this);"and

尝试:onclick="markActiveLink(this);"

function markActiveLink(el) {   
    alert($(el).attr("id"));
}

回答by jAndy

why using an inline handler? Move to unobtrusive js

为什么使用内联处理程序?转向不显眼的js

$(document).ready(function(){
  $('#myid').bind('click', function(){
     alert($(this).attr('id'));
  });
});

回答by Anpher

You have to pass the element to the function. JS itself isn't smarter than you :)

您必须将元素传递给函数。JS 本身并不比你聪明 :)

html:

html:

<a id="myid" class="first active" onclick="markActiveLink(this);" href="#home">Home</a>

js:

js:

function markActiveLink(e) {   
    alert(e.id);
}

回答by Simon

Do not use $(this)because it does accidentally return the element you added the bind. When you click on an inner element, it also returns the outer element.

不要使用,$(this)因为它会意外返回您添加绑定的元素。当您单击内部元素时,它还会返回外部元素。

<div id="outer">
    <div id="inner">

    </div>
</div>

You better use the following appearance:

您最好使用以下外观:

$("#outer").bind('click', function(e) {

    if(e.target.id === "inner")
    {
        alert("you clicked the inner element");
    }
    else
    {
        alert("you clicked the outer element");
    }
});

You can find a fiddle here: http://jsfiddle.net/vqab7jdo/1/

你可以在这里找到一个小提琴:http: //jsfiddle.net/vqab7jdo/1/

回答by Alireza

I try all the ways, spend almost 2 hours and finally found the best way I prefer try it:

我尝试了所有方法,花了将近 2 个小时,终于找到了我最喜欢尝试的最佳方法:

< div onclick="div_Clicked(this.id)" id="some"/>

    function div_Clicked(itemName) { alert(itemName); }