在与按钮相同的div块中获取跨度的内部文本

时间:2019-03-03 09:14:49

标签: javascript jquery

如何使用按钮在div块中获取跨度的内部文本。

html代码

<div class='itemDivImage'>
    <a href =" .$link_to_page. ">
        <img src=" .$read_row['Bild']." alt=" .$name. "/>
    </a>
    <br>
    <span>".$name."</span>
    <br>
    <span class='price'> Pris:
       <span class='penger2'> ". $read_row['Pris'] ."</span> kr
    </span>
    <br>
    <input type="button" name="' .$name. '" class="bayItem" value="Lägg i varukorg">
    <img src="'.$linkImgAAA. '" class="energysafe" alt="EnergySafe" />
</div>
<div>
    <img id="varukorg_img" src="img/varukorg.png" alt="Varukorg" name="0">
    <a href="#">Varukorg <span class="penger">0</span> kr</a>

jQuery代码

$(document).ready(function(){

$('.bayItem').click(function(){

        var penger = $('.penger').text();
        var penger2 = $('.penger2').text();

        penger = parseInt(penger);
        penger2 = parseInt(penger2);
            var result = penger + penger2;
            $('.penger').text(result);
            });

});

3 个答案:

答案 0 :(得分:1)

发现:

$(".bayItem").on('click', function () {
    console.log($(".itemDivImage").find("span").text());
})

您可以根据需要更改此脚本

答案 1 :(得分:1)

使用$('.penger')时,它将返回文档中所有匹配的跨度。

要限制为所需的范围,请先从按钮上移至包装div,然后再下移至相关跨度,例如:

$(".bayItem").click(function() {
    var wrapper = $(this).closest(".itemDivImage");
    var span = wrapper.find(".penger");
    console.log(span.text());
});

示例片段:

$(".bayItem").click(function() {
  var wrapper = $(this).closest(".itemDivImage");
  var span = wrapper.find(".penger");
  console.log(span.text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='itemDivImage'>
  <span>Row 1</span>
  <span class='price'> Pris:
       <span class='penger'>12.34</span> kr
  </span>
  <br>
  <input type="button" class="bayItem" value="Lägg i varukorg" />
</div>
<hr/>
<div class='itemDivImage'>
  <span>Row 2</span>
  <span class='price'> Pris:
       <span class='penger'>23.45</span> kr
  </span>
  <br>
  <input type="button" class="bayItem" value="Lägg i varukorg" />
</div>
<hr/>
<div class='itemDivImage'>
  <span>Row 3</span>
  <span class='price'> Pris:
       <span class='penger'>34.56</span> kr
  </span>
  <br>
  <input type="button" class="bayItem" value="Lägg i varukorg" />
</div>

答案 2 :(得分:0)

您必须使用“关闭” 例如:

config.js