首页 > 解决方案 > 为什么它只返回数组的第一个元素,而我已经打印了数组的所有值?

问题描述

嘿,

我想在 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']; ?>€&lt;/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。

提前感谢您的帮助!

标签: javascriptjqueryhtml

解决方案


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);
  }
}

推荐阅读