<div class="auswahl">
<select id="1Riegel">
<option value="Mix">Mix</option>
<option value="Schoko">Schoko</option>
<option value="Frucht">Frucht</option>
</select>
<select "id="1Shake">
<option value="Mix">Mix</option>
<option value="Schoko">Schoko</option>
<option value="Vanille">Vanille</option>
</select>
</div>
var check_attribute = $(this).parents('div.produkt').find('select');
$.each(check_attribute, function (index, value) {
var name = $(this).attr('id'),
wert = ' ' + $(value).find('option:selected').val();
attribute = name.substring(1)+wert;
console.log(attribute);
});
这将输出:
Riegel Frucht
摇摇摇晃
在控制台中...但是我需要一行,就像这样:
Riegel Frucht-Shake Schoko
有人可以帮我这个忙吗?
答案 0 :(得分:1)
您可以改用.map
来获取所有<select>
和所选选项字符串的数组,然后通过-
将这些字符串连接起来:
const output = $('select').map(function() {
return $(this).attr('id').slice(1) + ' ' + $(this).find('option:selected').val();
})
.get()
.join(' - ');
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="auswahl">
<select id="1Riegel">
<option value="Mix">Mix</option>
<option value="Schoko">Schoko</option>
<option value="Frucht" selected>Frucht</option>
</select>
<select id="1Shake ">
<option value="Mix ">Mix</option>
<option value="Schoko " selected>Schoko</option>
<option value="Vanille ">Vanille</option>
</select>
</div>
或者,您可能会完全避免使用jQuery,而无需为此类简单的事情添加一个大型库:
const output = Array.prototype.map.call(
document.querySelectorAll('select'),
select => select.id.slice(1) + ' ' + select.value
)
.join(' - ');
console.log(output);
<div class="auswahl">
<select id="1Riegel">
<option value="Mix">Mix</option>
<option value="Schoko">Schoko</option>
<option value="Frucht" selected>Frucht</option>
</select>
<select id="1Shake ">
<option value="Mix ">Mix</option>
<option value="Schoko " selected>Schoko</option>
<option value="Vanille ">Vanille</option>
</select>
</div>
答案 1 :(得分:0)
var line = '';
var check_attribute = $(this).parents('div.produkt').find('select');
$.each(check_attribute, function (index, value) {
var name = $(this).attr('id'),
wert = ' ' + $(value).find('option:selected').val();
attribute = name.substring(1) + wert;
if(line.lenght>0){
line += " - ";
}
line += attribute;
});
console.log(line);
此服务器的用途