我需要检索页面上每个下拉列表的所有选定值,并使用这些值填充无序列表。当然,每个项目都有一个新的 li 元素。
目前我有这个:
$(document).ready(function() {
$("select").each(function() {
var sel = "";
$(this).find(":selected").each(function() {
sel += $(this).text() + " ";
});
$(".size-result").text(sel);
});
});
如何使用它来创建新的 li 元素,然后插入文本?
多亏了wirey,我终于可以使用它了:
$(document).ready(function() {
$("select").change(function() {
var sel = "";
$(".option-select option:selected").each(function () {
sel += $(this).text() + " ";
});
$(".result").empty().append(sel);
});
});
有没有办法可以否定每个下拉列表的第一个条目?由于它是“选择...”或“选择一个...”值,我想阻止它显示,因为它是选择中的第一个值。
最佳答案
$(document).ready(function() {
var newLI = '';
$("select option:selected").each(function() {
newLI += '<li>' + $(this).text() + "</li>";
});
$('ulselector').append(newLI);
});
编辑:
您可以监听每个下拉列表中的更改并在每次更改时重新更新列表
$(document).ready(function() {
$('select').change(function(){ // <-- bind change event handler to the drop downs
var newLI = '';
$("select option:selected").each(function() { // <-- then iterate each time it changes
newLI += '<li>' + $(this).text() + "</li>";
});
$('ulselector').empty().append(newLI); //<-- empty() to remove old list and update with new list
});
});
再次编辑:
您可以检查所选值的索引是否为 0..如果是则不显示
$(document).ready(function() {
$('select').change(function() { // <-- bind change event handler to the drop downs
var newLI = '';
$("select option:selected").each(function() { // <-- then iterate each time it changes
if ($(this).index() !== 0) { // <-- only if not default
newLI += '<li>' + $(this).text() + "</li>";
}
$('ul').empty().append(newLI); //<-- empty() to remove old list and update with new list
});
});
});
关于jquery - 从下拉列表中检索选择并填充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12009343/