jQuery:获取点击元素的值 [英] jQuery: get value of clicked element

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

问题描述

我有这段代码:

<tr class="editField">
  <td>abc</td>
  <td>123</td>
  </td>
</tr>
<tr class="editField">
  <td>dfg</td>
  <td>456</td>
  </td>
</tr>

然后我用这个 javascript 用 jQuery 打开一个对话框:

And then I have this javascript to open a dialog with jQuery:

$( ".editField" ).click(function() {
        alert(...); // should get me 123
});

假设我点击第一个 tr 并且我会得到第二个 td 的内容(即 123),我应该写什么?

Suppose I click on first tr and I would get the content of second td (i.e 123), what should I write?

推荐答案

鉴于您目前的标记,我建议:

I'd suggest, given your current mark-up:

$( ".editField" ).click(function() {
        alert($(this).find('td:eq(1)').text());
});

但是,虽然这在给定的示例中有效,但将一些定义属性添加到您希望从中恢复值"的元素会更容易(并且随后更可靠),例如类-命名值",像这样给出 HTML:

But, while this works in the given example, it'd be much easier (and subsequently far more reliable) to add some defining attribute to the element from which you wish to recover the 'value', such as the class-name 'value', giving HTML like so:

<tr class="editField">
  <td>abc</td>
  <td class="value">123</td>
</tr>

还有 jQuery:

$( ".editField" ).click(function() {
        alert($(this).find('td.value').text());
});

或者,当然,如果值"始终是任何给定行(相关类的)的last td 元素,那么您可以改为使用:

Or, of course, if the 'value' will always be the last td element of any given row (of the relevant class), then you could instead use:

$( ".editField" ).click(function() {
        alert($(this).find('td:last').text());
});

顺便说一下,请注意您的 HTML 格式不正确,您的示例代码两行的最后一个单元格后面都有多余的 </td>.

Incidentally, please note that your HTML is malformed, you have a surplus </td> after the last cell in both rows of your sample code.

参考文献:

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

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