我有一个包含三个元素的数组,我循环遍历该数组以查看它的长度,以便它触发按钮三次点击动态添加输入选择框。每个数组值将在每个添加的选择框中进行,并查找是否与任何选项文本匹配,如果必须,则必须选择它。以下是我的代码,不知道我哪里出错了
var myArryValues = [
"Hello World",
"Javascript",
"Jquery"
]
for (var i = 0; i < myArryValues.length; i++) {
var bookIndex = 0;
$('#bookForm').on('click', '.mynewButton', function() {
$('.myDropdown').each(function(index) {
console.log("operatorString", operatorString);
var operatorCounter = 0;
var optionCounter = 0;
$(this).find('option').filter(function() {
if ($(this)[optionCounter] == myArryValues[operatorCounter]) {
$(this)[optionCounter].attr('selected', "selected");
operatorCounter++;
} else {
optionCounter++;
}
});
});
console.log("mynewButton");
bookIndex++;
var bookForm = $('#bookForm');
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.addClass('myDropdown-row')
.removeClass('hide')
.attr('data-book-index', bookIndex)
.attr('id', '');
bookForm.append($clone);
// Update the name attributes
$clone
.find('[name="myDropdown"]').attr('name', 'myDropdown[' + bookIndex + '].myDropdown').end()
})
// Remove button click handler
.on('click', '.removeButton', function() {
$(this).parents('.form-group').remove();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="row" id="bookForm" class="form-horizontal">
<div class="form-group">
<div class="col-md-2 button-div">
<button type="button" class="mynewButton rule-button">Add New
</button>
</div>
</div>
<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
<div class="row field-row">
<div class="col-md-2">
<select class="myDropdown" name="myDropdown">
<option value="Hello World">Hello World</option>
<option value="Javascript">Javascript</option>
<option value="Jquery">Jquery</option>
</select>
</div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:0)
在点击功能上试试这个
var data = ['bar','baz'];
for (var i = 0; i < data.length; i++) {
var s = $('<select id="'+i+'"/>');
for (var j = 0; j < data.length; j++) {
if (i==j) {
$('<option />', {value: data[j], text: data[j],selected:'selected'}).appendTo(s);
}else{
$('<option />', {value: data[j], text: data[j]}).appendTo(s);
}
}
s.appendTo('body');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
&#13;