栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用jquery更新select的所有选项

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用jquery更新select的所有选项

对于实际修改选项,您实际上并不需要jQuery。您可以通过分配框

length
属性的
options
属性来清除旧选项
SELECT
,然后通过
#add
和添加新选项
newOption()

这是使用jQuery作为XHR部分,然后直接执行选项的几个示例:

从数组中:

如果要从对象内的数组(在本例中为由

options
结果对象上的属性标识的数组)绘制数据:

JSON:

{  "options": [    {"value": "New1", "text": "New Option 1"},    {"value": "New2", "text": "New Option 2"},    {"value": "New3", "text": "New Option 3"}  ]}

Javascript:

$.ajax({  url: "http://jsbin.com/apici3",  dataType: "json",  success: function(data) {    var options, index, select, option;    // Get the raw DOM object for the select box    select = document.getElementById('theSelect');    // Clear the old options    select.options.length = 0;    // Load the new options    options = data.options; // Or whatever source information you're working with    for (index = 0; index < options.length; ++index) {      option = options[index];      select.options.add(new Option(option.text, option.value));    }  }});

现场例子

直接来自对象:

如果将对象的属性名称用作

option
值,并将属性值用作选项文本:

JSON:

{  "new1": "New Option 1",  "new2": "New Option 2",  "new3": "New Option 3"}

Javascript:

$.ajax({  url: "http://jsbin.com/apici3/2",  dataType: "json",  success: function(data) {    var name, select, option;    // Get the raw DOM object for the select box    select = document.getElementById('theSelect');    // Clear the old options    select.options.length = 0;    // Load the new options    for (name in data) {      if (data.hasOwnProperty(name)) {        select.options.add(new Option(data[name], name));      }    }  }});

现场例子


更新 :而不是

select.options.add(new Option(...));

您也可以:

select.options[select.options.length] = new Option(...);

现场例子

…我认为实际上我倾向于

add
options
类似数组的东西上使用该方法(我之所以不称其为数组,是因为它有一个方法
add
,该数组没有该方法;并且因为如果使用
push
,哪些数组
确实 有,但不起作用)。

我已经测试了两种方法

  • IE6,7,8(Windows)
  • Chrome(Linux和Windows)
  • Firefox(Linux和Windows)
  • Opera(Linux和Windows)
  • Safari(Windows)

…两者都起作用。也许有Mac的人可以为我在OS X上尝试Safari。

我想说两种方式都非常非常受支持。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/507043.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号