Jquery在div中获取div的文本

时间:2015-12-12 00:36:55

标签: jquery

您好我正在尝试将“描述”文本放在表格中(然后最终对“prix”执行相同操作)有很多“项目”因此我不能只为每个使用一个ID他们到目前为止,val的警报给了我一个空白,而我想要“HP portatif”

<div class="item" id="hp">
                <img class="imageItem" src=".\\produits\\portable1.jpg" />
                <div class="description">HP portatif </div>
                <div class="prix">350.95</div>
                <div class="ajouter" >Ajouter</div>
            </div>

$(".ajouter").click(function(){
            var val = $(this).children('div').text();
            alert(val);
            $('<tr>').appendTo('#corpsTableau');
            $('<td>'+val+'</td><td><input type=\"text\" style=\"float:right\"  /></td><td></td>').appendTo('#corpsTableau');
            $('</tr>').appendTo('#corpsTableau');   
        });

5 个答案:

答案 0 :(得分:2)

要获取正确的文本,您需要定位触发click事件的元素范围之外的元素。

没有。你可以做到的。

使用jquery .siblings()

$(".ajouter").click(function(){
                var val = $(this).siblings('div.description').text(); // gets the siblings of the  referenced element which has class 'description'
                alert(val);   
            });

http://jsfiddle.net/s8jvoq2n/1/

使用jquery .parent()

$(".ajouter").click(function(){
            var val = $(this).parent().find('.description').text(); // gets the parent of the referenced element and then find the div which has class 'description'
            alert(val); 
        });

http://jsfiddle.net/s8jvoq2n/2/

使用jquery .closest()

$(".ajouter").click(function(){
            var val = $(this).closest('div.item').find('.description').text(); // gets the closest occurring element of the referenced element with class 'item' and then find the div which has class 'description'
            alert(val); 
        });

http://jsfiddle.net/s8jvoq2n/3/

答案 1 :(得分:0)

因为你的目标是.ajouter类的子节点,其中没有。你可以像以下一样定位它:

var val = $(this).text(); 

var val = $('.ajouter').text(); 

答案 2 :(得分:0)

我有多种方式:

  $(this).siblings('.description').text()

小提琴http://jsfiddle.net/alsosun/n59d2toj/

答案 3 :(得分:0)

问题似乎出现在&#34; val&#34;的选择器上。试试这个:

var val = $(this).siblings('.description').text();

$(this)指的是你点击的元素div.ajouter。 然后,我们查看描述类的所有特定元素的兄弟姐妹。然后我们从该元素中获取文本。

答案 4 :(得分:0)

在您的情况下,我认为最好使用一个而不是 https://jsfiddle.net/xx4dL68u/

通过这种方式,您将添加&#34;项目&#34;只有一次给购物车命名。

$(".ajouter").one('click',function(){
    var description = $(this).siblings('.description').text();
    var corpsItem='<tr><td>'+description+'</td><td><input type="text" style="float:right"  /></td><td></td></tr>';
    $('#corpsTableau').append(corpsItem);
});
相关问题