jQuery:获取点击元素的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12187407/
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
jQuery: get value of clicked element
提问by BAD_SEED
I have this piece of code:
我有这段代码:
<tr class="editField">
<td>abc</td>
<td>123</td>
</td>
</tr>
<tr class="editField">
<td>dfg</td>
<td>456</td>
</td>
</tr>
And then I have this javascript to open a dialog with jQuery:
然后我用这个 javascript 用 jQuery 打开一个对话框:
$( ".editField" ).click(function() {
alert(...); // should get me 123
});
Suppose I click on first tr
and I would get the content of second td
(i.e 123), what should I write?
假设我点击第一个tr
,我会得到第二个td
(即123)的内容,我应该写什么?
回答by David says reinstate Monica
I'd suggest, given your current mark-up:
鉴于您目前的标记,我建议:
$( ".editField" ).click(function() {
alert($(this).find('td:eq(1)').text());
});
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:
但是,虽然这在给定的示例中有效,但将一些定义属性添加到您希望从中恢复“值”的元素会更容易(并且随后更可靠),例如类名“值” ',像这样给出 HTML:
<tr class="editField">
<td>abc</td>
<td class="value">123</td>
</tr>
And the jQuery:
和 jQuery:
$( ".editField" ).click(function() {
alert($(this).find('td.value').text());
});
Or, of course, if the 'value' will always be the lasttd
element of any given row (of the relevant class), then you could instead use:
或者,当然,如果“值”将始终是任何给定行(相关类)的最后一个td
元素,那么您可以改为使用:
$( ".editField" ).click(function() {
alert($(this).find('td:last').text());
});
Incidentally, please note that your HTML is malformed, you have a surplus </td>
after the last cell in both rows of your sample code.
顺便提一下,请注意您的 HTML 格式错误,</td>
在示例代码的两行中的最后一个单元格后面都有多余的内容。
References:
参考:
回答by Dhanasekar
try this:
尝试这个:
$( ".editField" ).click(function() {
var clickedValue = $(this).find('td:first').next().text();
alert(clickedValue );
});
fiddle link : http://jsfiddle.net/9cRRj/8/
小提琴链接:http: //jsfiddle.net/9cRRj/8/
回答by Wiks
$(document).bind("click", function (e) {
$(e.target).closest("li").toggleClass("highlight");
alert($(event.target).text());
});
this will directly give you the selected element id. $(event.target).text(); will give you the selected element text within a second.
这将直接为您提供所选元素 ID。$(event.target).text(); 将在一秒钟内为您提供选定的元素文本。
回答by Ghulam Dastgeer
$(function () {
$(".Cartbtn").click(function () {
var temp = {
"Id": $(this).data("itemid"),
"Name": $(this).data("itemname"),
"Price": $(this).data("itemprice"),
"Quantity": $(this).data("itemqty"),
"ImageUrl": $(this).data("itemimgurl"),
});