单击它或其子元素时如何获取被点击元素的ID?

时间:2022-03-03 20:33:42

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. 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类的

的ID。如果.button或其任何子项被单击,它应该返回具有.button类的特定div的ID。

This is what I have so far: New JSFiddle

这就是我到目前为止:新的JSFiddle

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

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. 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由三个按钮组成,每个按钮都有一个子

标签,并共享
作为其父级。

<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">. 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.

听取

上的点击的jQuery。它检索被点击元素的第一个类名,并将其存储在变量中。在这种情况下引出的响应是CSS样式背景颜色的更改,尽管这是任意的,并且会根据函数的使用而改变。

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. This could potentially * with other functions using the same method.

事实上,我在元素中添加了很多类,只是为了在点击上识别它们,这似乎不会很好地扩展,通常是一种糟糕的方法。这个方法也意味着我总是需要放置类名来标识在HTML类属性的开头选择了哪个元素。这可能会使用相同的方法与其他函数冲突。

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?

有没有更好的方法来识别从父母点击监听器中选择了哪个子元素,其中一个孩子可能有其他孩子也需要听众的相同响应?

3 个解决方案

#1


2  

EDIT based on the edited question:

编辑基于编辑过的问题:

I think that what you really want is the id of the element that triggered the event.
But by using e.target you have the target element... which is not necessarily the element that triggered the event.

我认为你真正想要的是触发事件的元素的id。但是通过使用e.target你有目标元素......这不一定是触发事件的元素。

See in this updated 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,
a data attribute can be usefull.

为了避免使用id或class作为标识符来确定单击的内容,数据属性可能很有用。

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-selected或data-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>

#2


0  

no need to id the subject, since it was the one clicked, i.e. e.target which with jQuery you cant select like $(e.target) without any trouble

不需要识别主题,因为它是单击的,即e.target与jQuery你不能选择像$(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>

#3


0  

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。

#1


2  

EDIT based on the edited question:

编辑基于编辑过的问题:

I think that what you really want is the id of the element that triggered the event.
But by using e.target you have the target element... which is not necessarily the element that triggered the event.

我认为你真正想要的是触发事件的元素的id。但是通过使用e.target你有目标元素......这不一定是触发事件的元素。

See in this updated 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,
a data attribute can be usefull.

为了避免使用id或class作为标识符来确定单击的内容,数据属性可能很有用。

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-selected或data-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>

#2


0  

no need to id the subject, since it was the one clicked, i.e. e.target which with jQuery you cant select like $(e.target) without any trouble

不需要识别主题,因为它是单击的,即e.target与jQuery你不能选择像$(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>

#3


0  

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。