我有以下标记
<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
我想要
cloneLayoutSelect
中的所有元素,其数据属性为data-multi-column="true"
data-label
的值input/select/radio/checkbox
值我尝试了以下内容:
var elements = $('*[data-multi-column="true"]');
$.each(elements, function(index, htmlElement) {
var element = $('<div><div/>').html(htmlElement).contents();
});
虽然它返回了我想要的结果,但我有两个问题
cloneLayoutSelect
中搜索它。<div class="col2">
感谢任何帮助或指示。
感谢。
答案 0 :(得分: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