[英]Get a field with jQuery when a button is clicked
我有一张满是约会的桌子。 每个约会都有两个按钮。 一种用于取消活动,一种用于接受活动。
当我单击按钮时,我正在努力在jQuery函数中获取appointmentId
ID。 您能给我一个提示怎么做吗? appointmentId
在表中作为隐藏的输入字段。
// my html code
<tr>
<td align="left">
<input type="hidden" name="appointmentId" value="234">
John Smith - 14.03.2013 at 9 o'clock
</td>
<td align="right">
<input type="button" id="acceptEvent" class="acceptEvent" value="Accept">
<input type="button" id="cancelEvent" class="cancelEvent" value="Cancel">
</td>
</tr>
// my jQuery code
$("body").delegate('.acceptEvent', 'click', function() {
console.log('accept event clicked');
// get the appointmentId here
});
$("body").delegate('.cancelEvent', 'click', function() {
console.log('cancel event clicked');
// get the appointmentId here
});
使用最接近来获取父级tr元素,然后选择隐藏字段。 这是正确答案的原因是因为它使用$(this)与click事件的上下文。 然后,它在DOM树中向上移动到您的根表行元素,并按名称选择子级。 这样可以确保您始终处于正确的行中。
编辑:我知道您已经选择了一个答案,但这确实让我感到困扰,因为它无法正常工作。 我不得不使用.children()使其走下两次,尽管您也可以使用.find('input [name =“ appointmentId”]')。 即使您已经选择了答案,也希望对您有所帮助。
$('.acceptEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
$('.cancelEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
假设您没有其他要键入的ID或类,则可以使用jQuery的Attribute Equals Selector来引用单击按钮的父tr
元素:
$('.acceptEvent').click(function() {
// get the appointmentId here
var appointmentId = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
在click
的功能,您可以访问与单击该按钮this
,所以你可以这样做:
$("body").on('click', '.cancelEvent', function() {
var input = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
我会那样做:
$("body").on('.acceptEvent', 'click', function() {
var id = $('input[name="appointmentId"]').val();
//Or search in the parent <tr>
var id = $(this).parent().find('input[name="appointmentId"]').val();
console.log('accept event clicked');
console.log('Id is ' + id);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.