select设置innerHMTL
发布日期:2021-08-13 18:30:23 浏览次数:2 分类:技术文章

本文共 1763 字,大约阅读时间需要 5 分钟。

select控件在标准浏览器下可以直接innerHTML设置内容,IE则不行。

HTML结构:

 

先看直接使用select.innerHTML

var form = document.forms["form1"];    var select = form["select1"];    select.innerHTML = '';

 

运行发现标准浏览器如chrome, firefox运行正常,DOM树为

IE(678)全家都呵呵了:

原因在于IE使用innerHTML给select赋值时会根据/^<\w\d['" ]>&/(尖括号中间的字母、数字,引号,空格)匹配的字符都干掉,无力吐槽。

 

2种解决思路

 

1、使用select的outerHTML或者父级的innerHMTL

var select = document.forms["form1"]["select1"];select.outerHTML = '';

 

outerHMTL IE系列和chrome是支持的,新版的FireFox也支持,国内Firefox浏览器份额低的可以忽略不计。如果嫌弃outerHTML,当然可以换innerHTML

document.forms["form1"].innerHTML = '';

  简单暴力

 

2、使用new Option创建select的options,这是比较推荐的方法。

var form = document.forms["form1"];    var select = form["select1"];    select.options.add(new Option("text", "value")); // 或 select.add(new Option("text", "value"))

  new Option创建一个option对象实例,依次接受text,value两个参数,text为option的文本值,value即为option的value值。

发散思维,几种常见的option操作做个汇总:

var form = document.forms["form1"];    var select = form["select1"];        // 增加    select.options.add(new Option("text1", "value1")); // 或 select.add(new Option("text1", "value1"))    select.options.add(new Option("text2", "value2")); // 或 select.add(new Option("text2", "value2"))        // 删除选中项,也可指定删除    var index = select.options.selectedIndex;    select.options.remove(select.index); // 或 select.remove(select.index)        // 全删    select.options.length = 0;    // 改text    select.options[select.selectedIndex].text = "text3";     // 改value    select.options[select.selectedIndex].value = "value3";    // 同时修改text | value    select.options[select.selectedIndex] = new Option("text3", "value3");        // 查    var text = select.options[select.selectedIndex].text;    var value = select.options[select.selectedIndex].value;

 

 

 

转载于:https://www.cnblogs.com/mr189/p/3698242.html

转载地址:https://blog.csdn.net/weixin_30697239/article/details/98258134 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:sp_helptext输出错行问题解决
下一篇:递归全排列字符串

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月28日 06时21分40秒