使用jquery获取并打印h2文本到另一个div

时间:2015-06-15 13:01:35

标签: jquery

我想从h2标签获取产品名称文本,并将其作为列表元素传递给另一个div。点击添加到购物车按钮,我想要这个活动。

(我有更多产品项目文章元素)

这是我的HTML。谢谢大家的帮助!

<article class="product-item">
    <div class="product-title title-preorder">
        <h2><a href="#">This is my product name here</a></h2>
        <span class="preorder">
        Avaible
        </span>
    </div>
    <div class="product-params">
        <div class="product-img">
            <img src="/image/10428.jpg" alt="image">
        </div>
        <div class="product-details">
            My description here
        </div>
    </div>
    <div class="product-cart">
        <div class="price">
            $45 
        </div>
        <div class="amount">
            <input id="345346" value="1" class="spinner" /> 
        </div>
        <a class="add-to-cart" ><i class="fa fa-shopping-cart"></i>Add to Cart</a>
    </div>
</article>

<div class="product-list">
    <ul>
        <li>I'd like to print h2 text here
        </li>
    </ul>
</div>

3 个答案:

答案 0 :(得分:0)

您可以使用text()获取标题文字,append()添加新的列表项

&#13;
&#13;
$('.add-to-cart').click(function(){
  $('.product-list ul').append('<li>'+$('h2').text()+'</li>');
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<article class="product-item">
    <div class="product-title title-preorder">
        <h2><a href="#">This is my product name here</a></h2>
        <span class="preorder">
        Avaible
        </span>
    </div>
    <div class="product-params">
        <div class="product-img">
            <img src="/image/10428.jpg" alt="image">
        </div>
        <div class="product-details">
            My description here
        </div>
    </div>
    <div class="product-cart">
        <div class="price">
            $45 
        </div>
        <div class="amount">
            <input id="345346" value="1" class="spinner" /> 
        </div>
        <a class="add-to-cart" ><i class="fa fa-shopping-cart"></i>Add to Cart</a>
    </div>
</article>

<div class="product-list">
    <ul>
        <li>I'd like to print h2 text here
        </li>
    </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

FIDDLE

$('.add-to-cart').click(function () {
  $('.product-list').find('li').text($('.product-title').find('a').text());
});

答案 2 :(得分:0)

我在你的帮助下解决了它。我不得不在函数中使用“最接近”的方法,现在它完美地工作。

$('.add-to-cart').click(function(){
   $('#cart-content-inner ul').append('<li>'+$(this).closest(".product-item").find('h2 a').text()+'</li>');
});