【问题标题】:Dynamically adding element to Select and setting the selectindex in JQuery将元素动态添加到 Select 并在 JQuery 中设置 selectindex
【发布时间】:2012-02-24 18:23:01
【问题描述】:

我创建了一个动态选择列表框,如下所示

for (var i in c) {
            //alert(c[i].IsDefault);
            if(c[i].IsDefault==true){
                //alert('found default');
                $("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
                temp = c[i].Code;
            }
            else{
                $("#AnsType").append("<option value='" + c[i].ID + "'>" + c[i].Code+ "</option>");
            }

        }

刷新了

$('#AnsType').selectmenu('refresh');

我尝试了所有这些方法并尝试在列表中选择第二个元素对我没有用。

$('#AnsType').val(temp.toString());
$('#AnsType').get(3).selectedIndex = 3;
$('select#AnsType').val('3');
$("#AnsType option[text='3']").attr("selected","selected") ;
$("#mydropdownlist").attr('selectedIndex', 1);
$('#AnsType').val(3);
$("#AnsType").attr('selectedIndex', 2);
$("#AnsType").val(c[parseInt(temp)].Code);
$("select#AnsType option[selected]").removeAttr("selected");
$("select#AnsType option[value='"+temp+"']").attr("selected", "selected");

这就是我的列表框的创建方式

<select id="AnsType" name="AnsType">
        <option value="1">Obokad</option>
        <option value="3">Egen bokning</option>
</select>

任何帮助表示赞赏,并提前感谢您的帮助..

【问题讨论】:

  • 你想做什么??
  • 我想选择列表中的第二个元素。
  • 在要保持选中状态的选项中添加 selected="selected" 属性。
  • $('#AnsType').get(3).selectedIndex = 3; - ID 选择器应该只返回一个元素(因为 ID 应该是唯一的!),所以我不确定您期望 get(3) 返回什么。

标签: javascript jquery jquery-selectors jquery-mobile


【解决方案1】:

如果您希望在创建菜单时预先选择某些元素,请将selected 属性添加到相应的选项元素:

if(c[i].IsDefault==true){
    $("#AnsType")
        .append("<option value='" + c[i].ID + " selected='selected'">" + c[i].Code+ "</option>");
    temp = c[i].Code;
}

请注意,您必须在以编程方式更改底层选择元素的值后再次刷新选择菜单:

$('#AnsType').val('3');
$('#AnsType').selectmenu('refresh');

Documentation

刷新更新自定义选择
这用于更新自定义选择以反映本机选择元素的值。如果选择中的选项数与自定义菜单中的项目数不同,它将重建自定义菜单。另外,如果你传递一个真实的参数,你可以强制重建发生

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-05
    • 2016-12-19
    • 1970-01-01
    • 2020-03-22
    • 2023-03-13
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    相关资源
    最近更新 更多