javascript - 为什么它只返回数组的第一个元素,而我已经打印了数组的所有值?
问题描述
嘿,
我想在 html 标签中获取值,但它只返回第一个值,我不知道为什么......(我想要类“iHidden”的 html 标签的值)
(我完全设法在我的 javascript 中使用 name="service[]" 获取第一个输入的值)
while($service = $req->fetch()){ ?>
<div class="form-control">
<input type="checkbox" name="service[]" value="<?= $service['price']; ?>" id="<?= $i++ ?>">
<p>id_service : <i class="iHidden"><?= $service['id_service']; ?></i></p>
<label for="<?= $service['service'] ?>"><?= $service['service']; ?></label>
<strong><?= $service['price']; ?>€</strong>
</div>
<?php } ?>
这是我的javascript:
for(var i = 0; i <= totalService; i++){
if($('#'+i).is(":checked")){
// For the first input (it works)
var total = $('#'+i).val();
globalTotal = parseInt(globalTotal )+ parseInt(total);
// End for the first input
// Here is the problem : it returns only the first value in my database...
getI[i] = $('.iHidden').html();
console.log(getI); // shows the first value
}
}
当它点击“Calculer prix des services”时,我希望它显示我检查的服务的 ID。如果我检查了 2,我希望它显示 2。
提前感谢您的帮助!
解决方案
该html()
方法返回集合中第一个元素的 HTML 内容。在您的情况下,.iHidden
选择所有带有 class 的元素iHidden
。
获取匹配元素集中第一个元素的 HTML 内容或设置每个匹配元素的 HTML 内容。
用于解决基于总元素的父元素选择的问题。Whereclosest()
方法可用于获取共同祖先和iHidden
使用方法获取元素find()
。
getI[i] = $('#'+i).closest('.form-control').find('.iHidden').html();
仅供参考: 来自 MDN 文档:
注意:使用除 ASCII 字母、数字、“_”、“-”和“.”以外的字符 可能会导致兼容性问题,因为它们在 HTML 4 中是不允许的。尽管在 HTML 5 中已经取消了此限制,但为了兼容性,ID 应该以字母开头。
所以最好以字母而不是数字开头 id 值。
例如 :
PHP
<input type="checkbox" name="service[]" value="<?= $service['price']; ?>" id="total<?= $i++ ?>">
JS
for (var i = 0; i <= totalService; i++) {
var $tot = $('#total' + i);
if ($tot.is(":checked")) {
var total = $tot.val();
globalTotal = parseInt(globalTotal) + parseInt(total);
getI[i] = $tot.closest('.form-control').find('.iHidden').html();
console.log(getI);
}
}
推荐阅读
- javascript - 当事件名称包含点时如何拦截自定义事件?
- python - 将一条曲线水平移动到另一条曲线
- python - 调用 Python 对象时超出 UNET 分段训练最大递归深度
- c++ - 如何在 C++ 中使用前向声明
- reactjs - React Hook Form 使用 Controller、yup 和 Material UI - 验证问题
- python - h5py 的性能瓶颈在哪里?
- python - 带有截距的 cvxpy 多线性回归
- node.js - 我想通过循环 node.js (discord.js) 来运行代码
- asp.net-core-mvc - ASP.NET Core MVC 中的离线和 PWA 功能
- amazon-web-services - 使用 aws lambda 执行时,aws lambda 测试抛出 InvalidS3ObjectException 错误,这是怎么回事?