如何从表单的这个实例中获取名为userID的类的值?我无法序列化表单,因为表单本身没有任何唯一标识符。
<form method="post">
<input type="hidden" name="userID" class="userID" value="<? echo $id; ?>" >
<input type="hidden" name="imageID" class="imageID" value="<? echo $row['newest_image']; ?>" >
<input type="button" style="margin-top:10px" name="delete_standard" class="delete_standard_btn" value="Delete">
</form>
目前我正在使用
var image_id = $(this).prev('.imageID').val();
var user_id = $(this).prev('.userID').val();
这给了我imageID ok而不是userID,如果我在表单中交换隐藏的输入,我可以获得userID而不是imageID。
答案 0 :(得分:3)
使用prevAll('.userID')
而不是prev('.userID')
。 prev
仅查看前一个兄弟,prevAll
查看所有之前的兄弟姐妹并按顺序返回它们(最接近的第一个)。由于最近的是第一个,因此在其上调用val()
将为您提供最近匹配的兄弟的值。
E.g:
var image_id = $(this).prevAll('.imageID').val();
var user_id = $(this).prevAll('.userID').val();
答案 1 :(得分:0)
如果$(this)是表单,则使用.find()。
$('.userID', this).val();
// or
$(this).find('.userID').val();
如果是按钮元素,请使用.prevAll()而不是.prev()。
$(this).prevAll('.userID').first().val();
答案 2 :(得分:0)
当您使用jQuery提交表单时,您的上下文this
将设置为当前表单元素。
所以你可以这样做:
$('form').on('submit', function (e) {
var $this = $(this),
image_id = $this.find('.imageID'),
user_id = $this.find('.userID');
}