jQuery从上面获取标签

luk*_*com 6 html jquery

我正在编写一个函数来在每次用户更新时更新订单收据,然后关闭产品弹出式叠加层.该函数搜索表单的每个输入,然后如果其值大于,则将信息添加到收据div 0.我试图获取.html()位于输入字段上方的标签元素,该元素描述当前项目,并将其用作收据中项目的描述.

我试过没用成功:

 - $this.closest('label').html() 
 - $this.prev('label').html()
 - $this.find('label').html()
 - this.element.find('label').html()
Run Code Online (Sandbox Code Playgroud)

这是我的代码.我正在讨论的部分是'标签是'部分......

function updateOrder(){

var items = '';
$('input').each(function(){
    var $this = $(this),
        i_value = $this.attr('value');

    if(i_value > 0){
      items += $this.attr('id') + ' Quantity: ' + i_value + '<br/>' 
      + 'label is: ' + $this.closest('label').html() + '<br/>';  
    }
});

$('#d_reciept').html(items);
Run Code Online (Sandbox Code Playgroud)

}

和一个示例表单项

<tr>
<td class="td_thumbs">
    <div>
        <a class="fancybox" data-fancybox-group="vinyl-banners" href="img/products/vinyl-corporateblue.jpg"> <img src="img/products/thumbs/vinyl-corporateblue-thumb.png" alt="vinyl c-blue"/></a>
        <label>Corporate Blue</label>
    </div>
</td>
<td>6</td>
<td>
    <input id="vinyl-blue" type="number" max="6" min="0" value="0"/>
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

Adi*_*dil 17

该函数closest首先给出了给定选择器的准确性ancestors,你的标签不在第一个祖先,而是在父tr中children,你需要转到父tr,然后使用find来搜索它的父级label.

$(this).closest('tr').find('label').html()
Run Code Online (Sandbox Code Playgroud)

要么

$(this).closest('tr :td:eq(0)').find('label').html()
Run Code Online (Sandbox Code Playgroud)