如何获取价值​使用jquery从具有相同类名的多个元素中提取



我用打印出一个带有foreach循环的表,每行都有一个带有隐藏输入和提交按钮的表单,比如这个

<form>
<input type="hidden" value="<?php echo $item['name'] ?>" class="get_name">
<input type="hidden" value="<?php echo $item['email'] ?>" class="get_email">
<input type="hidden" value="<?php echo $item['address'] ?>" class="get_address">
<input type="hidden" value="<?php echo $item['birthday'] ?>" class="get_birthday">
<button type="submit" class="Add">Add</button>
</form>

我想问的是,当我点击一行中的提交按钮时,如何获得该行中的值。我使用了$('.classname').val(),得到的唯一结果是表中第一行的值。

您可能正在使用val(),它按预期工作:

Get the current value of the first element....

如果使用.each()循环遍历元素,则可以检索所有元素的值,如下所示:

$("input[type=hidden]").each(function() {
console.log($(this).val())
}

无意冒犯,但这个问题很琐碎,只需要一些基本的jQuery知识或如何在jQuery文档中搜索。我建议您不要直接进入您的解决方案,而是像这样介绍jQuery,以了解如何使用jQuery:遍历DOM和提取数据

https://www.tutorialspoint.com/jquery/index.htm

我不确定是否能清楚地理解您想要实现的目标,但获取一行中所有值的方法是:

var row = {};
$('input[type=hidden]').each(function () {
row[$(this).attr('class')] = $(this).val();
});
console.log(row);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="hidden" value="<?php echo $item['name'] ?>" class="get_name">
<input type="hidden" value="<?php echo $item['email'] ?>" class="get_email">
<input type="hidden" value="<?php echo $item['address'] ?>" class="get_address">
<input type="hidden" value="<?php echo $item['birthday'] ?>" class="get_birthday">
<button type="submit" class="Add">Add</button>
</form>

最新更新