2012-12-13 53 views
6

我正在編寫一個函數,在用戶每次更新時更新訂單收據,然後關閉產品彈出疊加層。 該函數搜索表單的每個輸入,然後將其信息添加到收據div,如果其值大於0。我試圖獲取位於輸入字段上方的標籤元素的.html()並描述了當前項目,並將其用作收據中項目的描述。jQuery從上面獲取標籤

我一直在使用沒有成功嘗試:

- $this.closest('label').html() 
- $this.prev('label').html() 
- $this.find('label').html() 
- this.element.find('label').html() 

這裏是我的代碼。我講的一節是「標籤」的一部分......

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); 

}

和樣表項

<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> 

回答

16

功能closest給你定選擇的第一accurance在ancestors中,您的標籤不在第一個祖先中,而是在父親tr children中,您需要轉到父tr,然後使用find來搜索其父親label

$(this).closest('tr').find('label').html() 

$(this).closest('tr :td:eq(0)').find('label').html() 
+0

輝煌! $(this).closest('tr')。find('label')。html()working :) – lukeocom