2017-07-05 47 views
-1

的ID我有一個結構:獲取以前選擇標籤

<div class="input_fields_wrap"> 
    <div class="row"> 
    <select id="house-1-room-1"><?php echo $options; ?></select> 
    <input type='text' class='name' name='house-1-room-size-1' placeholder='Room Size'> 
    </div> 
</div> 
<button class="add_field_button">Add Another Room</button> 

add_field_button點擊,我試圖讓以前select標籤的ID,在我的情況下,它是house-1-room-1使用jQuery(或vanila JS) 。

我已經試過:

$(this).parent().prev("select").attr('id'); 

$(this).prev("div").closest("select").attr('id'); 

及以上無濟於事許多其他組合。

請幫忙!

+0

我認爲你需要像這樣: '$(本).prev()。find(「select」)。attr('id');' –

+0

請注意,要找到您首先找到節點的id。因此,提取id,然後用'$('#myid')搜索文檔,找到與提取id相同的確切節點,這是浪費時間的很大一部分。 – James

回答

3

用途:

$(this).prev("div").find("select").attr('id'); 

.closest()在DOM層次了find()搜索層次。

1

需要使用find()

$(this).prev("div").find("select").attr('id'); 

.closest()是相反的,去從底部到頂部。 .find()將從層次結構中的當前位置開始。

1

找到以前的元素,發現內

$(this).prev().find('select').attr('id') 

選擇標籤這應該工作

這裏是一個小提琴https://jsfiddle.net/fxabnk4o/3/