javascript 如何获取li元素的id

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

How to get the id of a li element

javascriptjqueryhtml

提问by goes

I have a list of elements created dinamically. Each item has an ID. I didn't find how to get the id of each element when it is clicked.

我有一个动态创建的元素列表。每个项目都有一个 ID。我没有找到如何在单击时获取每个元素的 id。

Nothing is working out... :(

什么都没有解决... :(

回答by PSL

Just do this.id. Inside your handler thiswill be the clicked element and you can access its idas a property.

就做this.id。在您的处理程序this中将是被点击的元素,您可以将其id作为属性访问。

Ex:

前任:

   $(elem).click(function(){
       var id = this.id; //Here this is the DOM element and you can access its id property
       ///Do something..
   })

回答by Ivotje50

Assuming you are using jQuery:

假设您正在使用 jQuery:

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

回答by Travis J

When a click event is fired, the element that was the target of the click is stored as thisinside of the jquery callback

当点击事件被触发时,作为点击目标的元素被存储this在 jquery 回调中

$("li").click(function(){
 var elementClicked = this;
 var elementClickedId = this.id;
});

回答by Zword

Using pure javascript you can do something like this:

使用纯 javascript,您可以执行以下操作:

<script>
function getID(a)
{
    document.getElementById("showid").innerHTML = a;
}
</script>
<li id="n1" onclick="getID(this);">Item1</li>
<li id="n2" onclick="getID(this);">Item2</li>
<li id="n3" onclick="getID(this);">Item3</li>

<div id="showid"></div>