在JQuery中访问<p>标记值

时间:2016-07-18 12:12:55

标签: javascript jquery html

我的目标是有一个按钮,一旦点击,添加一定的内容 &#34; P&#34;列表中的标记(与按钮相关)。我到目前为止的代码是;

HTML:

<a href="GardenFurniture.html">
  <div class="product">
    <figure class="col-sm-3" height="220" id="product" >
    <p class="PTitle"> <strong>Stylish Table and Chairs Set</strong></p>
    <img src="GardenFurnitureImages/small.jpg"/>
  </a>
    <p style="display: inline" class="price"> Price: £499 </p>
    <input style="display: inline" type='button' value='Add to Basket' class='addBasket'>
  </figure>
</div>

使用Javascript:

$('.addBasket').click(function() {
    var basketProduct = $(this).parent('.PTitle').val();
    $('<li>').text(basketProduct).appendTo('.BasketBar');
});

我正在尝试将Ptitle(时尚桌椅套装)的内容附加到列表BasketBar

此代码只是在列表中添加了一个空格,以便了解如何获得所需的输出?

1 个答案:

答案 0 :(得分:2)

首先你的html结构无效,标签的开头和结尾都不合适:

<a>代码和<figure>代码未正确关闭,因此请先查看并先修正html

我通过更改一些html来发布答案:

$('.addBasket').click(function(){
  // here we have used .siblings as we need to get text of same level element
  var basketProduct = $(this).siblings('.PTitle').text(); // use .text() for getting text inside any element
  alert(basketProduct)
  $('<li>').text(basketProduct).appendTo('.BasketBar');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class="product">
  <figure class="col-sm-3" height="220" id="product" >
    <p class="PTitle"> <strong>Stylish Table and Chairs Set</strong></p>
    <img src="GardenFurnitureImages/small.jpg"/>
    <p style="display: inline" class="price"> Price: £499 </p>
    <input style="display: inline" type='button' value='Add to Basket' class='addBasket'>
  </figure>
</div>