简体   繁体   English

当单击元素或其子元素时,如何获取其ID?

[英]How to get the ID of a clicked element, when it or its children are clicked?

UPDATED 更新

I think I may have inadvertently made the question confusing. 我想我可能会不经意间使这个问题感到困惑。 This is an update that is more specific with updated code based on comments and answer I have been given so far. 到目前为止,这是一个更新,其中包含基于注释和答案的更新代码。 Thank you to everyone that has taken the time to comment and answer. 感谢所有花时间发表评论和回答的人。

How can I get the ID of a <div> with the class of .button when I have a click listener for .button . 我怎样才能得到一个的ID <div>与类的.button时,我有一个点击监听.button If .button or any of its children are clicked, it should return the ID for that particular div with the class of .button . 如果.button或其任何子级,则应返回带有.button类的特定div的ID。

This is what I have so far: New JSFiddle 到目前为止,这是我所拥有的: New JSFiddle

HTML HTML

<div class="row">
  <div id="b1" class="button">
    <h2>Button 1</h2>
  </div>
  <div id="b2" class="button">
    <h2>Button 2</h2>
  </div>
  <div id="b3" class="button">
    <h2>Button 3</h2>
  </div>
</div>

jQuery jQuery的

var selected = "";

$('.button').on('click', function(e) {
  selected = e.target.id;

  $('.button').css('backgroundColor', '#becde5');
  $('#' + selected).css('backgroundColor', '#3b71c6');

  $('#selected').html(selected);
});

This is almost correct but does not propagate, if I click on a <h2> the function does not work. 这几乎是正确的,但不会传播,如果我单击<h2>该功能将无法正常工作。 However if I click on the .button div itself it works. 但是,如果我单击.button div本身,它将起作用。

Initial Question 最初的问题

I am trying to create a general function that can identify what child was selected from its parents click listener. 我正在尝试创建一个通用功能,该功能可以识别从其父级单击侦听器中选择了哪个孩子。 The child may have its own children that would all be considered part of the same element so that if any of these children where selected they should also elicit the same response from the click listener. 子级可能拥有自己的子级,这些子级都将被视为同一元素的一部分,因此,如果选择了这些子级中的任何一个,它们也应从点击侦听器中引起相同的响应。

This is an example of what I have working so far: JSFiddle 这是到目前为止我工作的一个示例: JSFiddle

HTML consisting of three buttons that all have one child <h2> tag and share the <div class="row"> as their parent. HTML由三个按钮组成,这些按钮都具有一个子<h2>标记,并共享<div class="row">作为其父代。

<div class="row">
  <div class="b1 button">
    <h2 class="b1">Button 1</h2>
  </div>
  <div class="b2 button">
    <h2 class="b2">Button 2</h2>
  </div>
  <div class="b3 button">
    <h2 class="b3">Button 3</h2>
  </div>
</div>

jQuery that listens for a click on <div class="row"> . 侦听<div class="row">的单击的jQuery。 It retrieves the first class name of the clicked element and stores it in a variable. 它检索被单击元素的第一类名称,并将其存储在变量中。 The elicited response in this case is a change of the CSS style background-color though this is arbitrary and would change depending on the use of the function. 在这种情况下,引起的响应是CSS样式background-color的变化,尽管这是任意的,并且会根据功能的使用而变化。

var selected = "";

$('.row').on('click', function(e) {
  selected = e.target.className.split(" ")[0];

  $('.b1, .b2, .b3').css('backgroundColor', '#becde5');
  $("." + selected).css('backgroundColor', '#3b71c6');

  $('#selected').html(selected);
});

The fact that I am adding a lot of classes to elements purely to identify them on a click seems like it would not scale very well and is generally a bad approach. 我仅在单击时就向元素添加很多类以识别它们的事实似乎无法很好地扩展,并且通常是一种不好的方法。 This method also means that I would always have to put the class name that identifies what element was selected at the beginning of its HTML class attribute. 此方法还意味着,我将始终必须将标识所选元素的类名称放在其HTML class属性的开头。 This could potentially clash with other functions using the same method. 使用相同的方法可能会与其他功能发生冲突。

Is there a better way to identify what child element was selected from its parents click listener, where a child may have other children that also require the same response from the listener? 有没有更好的方法来识别从其父级单击侦听器中选择了哪个子元素,一个孩子可能还有其他的孩子也需要听众提供相同的响应?

EDIT based on the edited question: 基于编辑的问题编辑

I think that what you really want is the id of the element that triggered the event. 我认为您真正想要的是触发事件的元素的id
But by using e.target you have the target element... which is not necessarily the element that triggered the event. 但是通过使用e.target您可以拥有target元素...不一定是触发事件的元素。

See in this updated Fiddle . 请参阅此更新的Fiddle

So simply use $(this) as the selector to retrieve the id... Using .attr("id") . 因此,只需使用$(this)作为选择器来检索ID ...使用.attr("id")

;) ;)



Answer to the initial question : 回答第一个问题
To determine what can be "selected", I used a "clickable" class. 为了确定可以“选择”的内容,我使用了“可点击”类。

To avoid using id or class as an identifier to determine what has been clicked, 为避免使用idclass作为标识符来确定已单击的内容,
a data attribute can be usefull. data属性可能有用。

I used data-id ... But you can use whatever you want, like: data-selected or data-target , and assign whatever value to it. 我使用了data-id ...但是您可以使用任何想要的东西,例如: data-selecteddata-target ,并为其分配任何值。

In the below code, I made two exactly identical rows, except their data-id value. 在下面的代码中,我做了两行完全相同的行,除了它们的data-id值。

 var selected = ""; $('.clickable').on('click', function(e) { e.stopPropagation(); // To prevent bubbling. // Reset all bg colors $('.button').css('backgroundColor', 'initial'); $('.row').css('backgroundColor', 'initial'); // Find exactly what was clicked if ($(this).hasClass("row")) { var row = $(this).data("id"); selected = row + " (whole)"; } if ($(this).hasClass("button")) { // Find in which row var row = $(this).closest(".row").data("id"); var btn = $(this).data("id"); selected = btn + " in " + row; } // Pale all buttons $('.button').css('backgroundColor', '#becde5'); // Change bg color of the selected element $(this).css('backgroundColor', '#3b71c6'); $('#selected').html(selected); }); 
 .row { display: table; width: 100%; color: white; border-spacing: 20px; } .button { display: table-cell; border-radius: 12px; background-color: #6fa1f2; text-align: center; } #selected { font-size: 30px; color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>Selected : <span id="selected">no selection</span></span><br> <div class="row clickable" data-id="row1"> <div class="button clickable" data-id="btn1"> <h2>Button 1</h2> </div> <div class="button clickable" data-id="btn2"> <h2>Button 2</h2> </div> <div class="button clickable" data-id="btn3"> <h2>Button 3</h2> </div> </div> <br> <div class="row clickable" data-id="row2"> <div class="button clickable" data-id="btn1"> <h2>Button 1</h2> </div> <div class="button clickable" data-id="btn2"> <h2>Button 2</h2> </div> <div class="button clickable" data-id="btn3"> <h2>Button 3</h2> </div> </div> 

no need to id the subject, since it was the one clicked, ie e.target which with jQuery you cant select like $(e.target) without any trouble 无需指定主题,因为它是单击的对象,即e.target ,使用jQuery可以像$(e.target)一样$(e.target)选择

then you need .closest('.button') to search up to the parent .button (if any) 那么您需要.closest('.button')来搜索父.button (如果有)

 $('.row').on('click', function(e) { $('.row > .button').css('backgroundColor', '#becde5'); $(e.target).closest('.button').css('backgroundColor', '#3b71c6'); console.log($(e.target).html()); }); 
 .button { cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div class="row"> <div class="button"> <h2>Button 1</h2> </div> <div class="button"> <h2>Button 2</h2> </div> <div class="button"> <h2>Button 3</h2> </div> </div> 

If you avoid giving an identifier (classes, IDs, etc) you'd need to do some manual checking for tag type to see what you clicked on (so basically, an identifier as well) 如果您避免提供标识符(类,ID等),则需要对标记类型进行一些手动检查,以查看所单击的内容(因此,基本上也包括标识符)

Here's an example, and not very memory efficient method jsfiddle example 这是一个示例,并不是非常高效的内存方法jsfiddle示例

$('.row, .row  *').on('click', function(e) {
  e.stopPropagation()    

  $('.button').removeClass('active')
  $('.button').css('backgroundColor', '#becde5');

  $(this).toggleClass('active')

  $('#selected').html(e.target.tagName + ': ' + e.target.className);
});

If you bind a click to div.row and clicked the h2 tag inside the button, and want to manipulate the h2 tag, you could check its tagName- but that less scalable than your OP. 如果将单击绑定到div.row并单击按钮内的h2标签,并且想要操纵h2标签,则可以检查其tagName,但可扩展性低于OP。

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

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