如何获取属性类型及其值

时间:2019-03-05 18:02:15

标签: javascript jquery

这是我的代码

  foreach ($data as $key => $value) {
        ?>
        <div class="col-md-4">


                <div style="border: 1px solid #ddd">
                    <img width="200px" height="200px" src="<?= $value["image"]; ?>">
                    <h4 class="text-info"><?= $value["name"]; ?></h4>
                    <h4 class="text-info"><?= $value["price"]; ?></h4>
                    <input type="number" class="form-control" value="1" name="quantity">
                    <input type="hidden" name="name" value="<?= $value["name"]; ?>">
                    <input type="hidden" name="price" value="<?= $value["price"]; ?>">
                    <input type="button" class="btn btn-success" name="add" value="Sepete Ekle" id="add">
                </div>

        </div>
        <?php

单击按钮后,如何获取属性type = hidden和name = price

1 个答案:

答案 0 :(得分:1)

jQuery示例处理添加按钮的click事件,并找到同级 price 。它将这个值写入控制台。

请查看,

siblings()-DOM遍历功能

CSS Attribute Selectors

$("input.btn[name='add']").click(function(e) { //the click of the add button
  console.log($(this).siblings("input[type='hidden'][name='price']").val()); //write the val of the hidden field
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4">


  <div style="border: 1px solid #ddd">
    <img width="10" height="10" src="">
    <h4 class="text-info"></h4>
    <h4 class="text-info"></h4>
    <input type="number" class="form-control" value="1" name="quantity">
    <input type="hidden" name="name" value="one">
    <input type="hidden" name="price" value="$1">
    <input type="button" class="btn btn-success" name="add" value="Sepete Ekle" id="add">
  </div>

</div>
<div class="col-md-4">


  <div style="border: 1px solid #ddd">
    <img width="10" height="10" src="">
    <h4 class="text-info"></h4>
    <h4 class="text-info"></h4>
    <input type="number" class="form-control" value="2" name="quantity">
    <input type="hidden" name="name" value="two">
    <input type="hidden" name="price" value="$2">
    <input type="button" class="btn btn-success" name="add" value="Sepete Ekle" id="add">
  </div>

</div>