简体   繁体   English

单击时如何获取元素的ID-javascript

[英]How to get id of an element when clicked on it - javascript

I am developing a canvas application on which a user can draw various shapes. 我正在开发一个画布应用程序,用户可以在其上绘制各种形状。 Various elements are drawn using d3.js. 使用d3.js绘制各种元素。 I want to use jsplumb to connect two SVG elements for which I need the id of each element when it is clicked on. 我想使用jsplumb连接两个SVG元素,单击它们时需要它们的每个元素的ID。 Each element has an id that is generated by code when it is drawn and thus I don't know it before hand. 每个元素都有一个ID,该ID是在绘制时由代码生成的,因此我事先并不知道。

Is there a javascript implementation by which I can get the id of the elements on which I click? 是否有一个JavaScript实现可用来获取单击的元素的ID? I wouldn't preferably want to add '' on each element that is being drawn on the canvas. 我最好不要在画布上绘制的每个元素上添加''。

Can anyone suggest a way to do this? 有人可以建议一种方法吗?

You can use something like this 你可以用这样的东西

<script type='text/javascript'>
    doClick = function (sender){
    alert(sender.id);
}
</script>

<div id='a1' onclick='doClick(this)'>div1</div>
<div id='a2' onclick='doClick(this)'>div2</div>

https://jsfiddle.net/dy47dbvp/3/ https://jsfiddle.net/dy47dbvp/3/

You can simply access an element's ID using that element's attributes 您只需使用该元素的属性即可访问该元素的ID

var elemID = droppedElement.attr('id');

To get the id of the clicked Element: 获取点击元素的ID:

$('#container').on('click', '.droppedElement', function (e) {
      var elemID = droppedElement.attr('id');
}

The container is your canvas id and the droppedElement is the variable that captures the svg element or the clone of the svg element(if that is your case) 容器是您的画布ID,而droppedElement是捕获svg元素或svg元素的克隆的变量(如果是这种情况)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM