2015-03-19 111 views
0

我有下面的標記與數據選擇元素屬性

<div class="cloneLayoutSelect"> 
    <div class="col2"> 
     <select name="ingredients[0][name]" id="ingredient" class="select" data-multi-column="true" data-label="Ingredient"> 
      <option value="0">Carrot</option> 
      <option value="1">Milk</option> 
      <option value="2">Yogurt</option> 
     </select> 
    </div> 
    <div class="col2"><input name="ingredients[0][quantity]" id="quantity" class="form-control" placeholder="Quantity" data-multi-column="true" data-label="Quantity" value="" type="text"></div> 
    <div class="col1 text-right"><button class="btn btn-default multi-column-2"><i class="fa fa-plus"></i></button></div> 
    <div class="clearfix clear"></div> 
</div> 

button.multi-column-2點擊我要

  • 獲取父DIV cloneLayoutSelect中的所有元素,並具有的data-multi-column="true"
  • 數據屬性
  • 獲得前一場比賽的個人元素data-label的價值
  • 獲取從以前的比賽的單個元件值

我試過如下:

var elements = $('*[data-multi-column="true"]'); 
$.each(elements, function(index, htmlElement) { 
    var element = $('<div><div/>').html(htmlElement).contents(); 
}); 

雖然它返回我想要的結果,我有兩個問題

  1. 它會搜索所有html標記,這不是我想要的,我只想在其父元素cloneLayoutSelect內搜索它。
  2. 它消除內<div class="col2">

任何幫助或指針所有HTML表示讚賞。

謝謝。

+1

http://jsfiddle.net/arunpjohny/0e2zbaq8/1/ - 你到底在做每個循環 – 2015-03-19 03:35:54

+1

http://jsfiddle.net/arunpjohny/0e2zbaq8/2/ – 2015-03-19 03:37:50

+0

_「它搜索所有html標記,這不是我想要的,我只想在其父元素cloneLayoutSelect內搜索它」 - - 然後把它加在你的選擇器上,或者在這些元素上使用'find()'。 – CBroe 2015-03-19 03:40:05

回答

1

您需要使用相對查找的元素,因此

$('button.multi-column-2').click(function() { 
    var $this = $(this); 
    //use a relative search 
    //we are finding the .cloneLayoutSelect ancestor of the clicked(referred by `this`) and is finding descendant elements with the attribute [data-multi-column="true"] 
    var $elements = $this.closest('.cloneLayoutSelect').find('*[data-multi-column="true"]'); 
    $elements.each(function() { 
     //for each element found we can read the data-label and value 
     var $el = $(this), 
      label = $el.data('label'), 
      value = $el.val(); 
     console.log(label, value) 
    }) 
}) 

演示:Fiddle