jQuery:从单击的div中获取价值 [英] jquery: get value from clicked div

查看:49
本文介绍了jQuery:从单击的div中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

等每个$ i都不同.

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

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

在标准JS中,我将使用onClick($ i). 在jQuery中,我只是不知道如何选择该值.

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

推荐答案

如果您没有其他方法来标识<div>元素,则会在 every 在页面上.

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').click(function() {
    var text = $(this).text();
    // do something with the text
});

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

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

如果只希望对某些<div>元素使用click事件,则最好是添加一个类,然后根据该类选择正确的类.

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

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

HTML

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

<div>some other div</div>

如果<div>元素都在同一祖先元素内,则可以使用 .delegate() 而是将一个处理程序放在祖先上,以处理内部的所有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.

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

HTML

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

(需要jQuery 1.4或更高版本)

这篇关于jQuery:从单击的div中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆