jquery:从单击的 div 中获取值

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

jquery: get value from clicked div

jquery

提问by Jeffz

<div>'.$i.'</div>

$i is auto generated by loop - which could lead to:

$i 由循环自动生成 - 这可能导致:

<div>'.$i.'</div>
<div>'.$i.'</div>
<div>'.$i.'</div>

etc. where each $i is different.

等等,其中每个 $i 是不同的。

How do I get value of particular $i (using jQuery), when div is clicked.

单击 div 时,如何获取特定 $i 的值(使用 jQuery)。

In standard JS I would use onClick($i). In jQuery I just do not know, how to pick that val.

在标准 JS 中,我会使用 onClick($i)。在 jQuery 中,我只是不知道如何选择那个 val。

回答by user113716

If you don't have any other way to identify the <div>elements, this would place a handler on every<div>on the page.

如果您没有任何其他方法来识别<div>元素,这将在页面上的每个元素上放置一个处理程序<div>

$('div').click(function() {
    var text = $(this).text();
    // do something with the text
});

The .text()method will return the text content for that <div>, (as well as any nested elements).

.text()方法将返回该<div>, (以及任何嵌套元素)的文本内容。

If you only wanted the clickevent on certain <div>elements, the best is to add a class, and select the correct ones based on that.

如果你只想要click某些<div>元素上的事件,最好是添加一个类,并根据它选择正确的类。

$('div.myClass').click(function() {
    var text = $(this).text();
    // do something with the text
});

HTML

HTML

<div class="myClass">'.$i.'</div>
<div class="myClass">'.$i.'</div>
<div class="myClass">'.$i.'</div>

<div>some other div</div>

If the <div>elements are all within the same ancestor element, you could use .delegate()instead, which will place one handler on the ancestor to handle all divs inside.

如果<div>元素都在同一个祖先元素中,您可以改用.delegate()它,它将在祖先元素上放置一个处理程序来处理内部的所有 div。

$('#parentID').delegate('div.myClass', 'click', function() {
    var text = $(this).text();
    // do something with the text
});

HTML

HTML

<div id="parentID">
    <div class="myClass">'.$i.'</div>
    <div class="myClass">'.$i.'</div>
    <div class="myClass">'.$i.'</div>
</div>

(Requires jQuery 1.4 or later)

(需要 jQuery 1.4 或更高版本)

回答by Pablo Fernandez

$('div').click(function(event){
  alert($(this).text());
});

A more efficient solution (since it seems you have a lot of <div>s would be to add a live event to the wrapping element of those, like this:

一个更有效的解决方案(因为看起来你有很多<div>s 将向那些的包装元素添加一个实时事件,如下所示:

$('#container').live('click', function(event){
   if(event.target.tagName == "DIV") alert($(event.target).text());
});