jquery:从clicked div获取值

Jef*_*ffz 7 jquery

<div>'.$i.'</div>
Run Code Online (Sandbox Code Playgroud)

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

<div>'.$i.'</div>
<div>'.$i.'</div>
<div>'.$i.'</div>
Run Code Online (Sandbox Code Playgroud)

每个$ i不同的地方.

当单击div时,如何获得特定$ i的值(使用jQuery).

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

use*_*716 17

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

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

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

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

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

HTML

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

<div>some other div</div>
Run Code Online (Sandbox Code Playgroud)

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

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

HTML

<div id="parentID">
    <div class="myClass">'.$i.'</div>
    <div class="myClass">'.$i.'</div>
    <div class="myClass">'.$i.'</div>
</div>
Run Code Online (Sandbox Code Playgroud)

(需要jQuery 1.4或更高版本)


Pab*_*dez 5

$('div').click(function(event){
  alert($(this).text());
});
Run Code Online (Sandbox Code Playgroud)

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

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