无刷新增加select(下拉框)中的option

本文仅献给along!

项目中有个无刷新增加select(下拉框)中的option的需求,在div中可以直接用document.getElementById(“id”).innerHTML多输出一个div。但是用select(下拉框)的id,输出option这个方法不行,下拉框里的option的标签都没了;

看例子:

转载请注明出处:https://www.html.cn

=========================================

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
??? <head>
??????? <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
??????? <title>Untitled Document</title>
???????
??? </head>
??? <body>
??????? <select name=”select4″ id=”MyFriend1_ddlFrindKind” class=”slt03″>
??????????? <option title=”好友分组” value=”1″ selected=”selected”>好友分组</option>
??????????? <option title=”好友分组” value=”2″>顺快速扩大</option>
??????? </select>
??<script type=”text/javascript”>
???var sel1 = document.getElementById(“MyFriend1_ddlFrindKind”).innerHTML;
???sel1+=”<option title=\”好友分组\” value=\”3\”>好友分组3</option>”
???alert(sel1);
???document.getElementById(“MyFriend1_ddlFrindKind”).innerHTML=sel1;
??????? </script>
??? </body>
</html>

=========================================

解决方案:

用JS的DOM操作,在select(下拉框)下使用document.createElement创建一个option标签,并赋值;

看例子:

=========================================

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
??? <head>
??????? <meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
??????? <title>Untitled Document</title>
???????
??? </head>
??? <body>
??????? <select name=”select4″ id=”MyFriend1_ddlFrindKind” class=”slt03″>
??????????? <option title=”好友分组” value=”1″ selected=”selected”>好友分组</option>
??????????? <option title=”好友分组” value=”2″>顺快速扩大</option>
??????? </select>
??<script type=”text/javascript”>
???var allOption = document.createElement(“option”);
???allOption.text = “好友分组3”;
???allOption.value = document.getElementById(“MyFriend1_ddlFrindKind”).length+1;?
???document.getElementById(“MyFriend1_ddlFrindKind”).options.add(allOption);
??????? </script>
??? </body>
</html>

=========================================

赞(0) 打赏
未经允许不得转载:WEB前端开发 » 无刷新增加select(下拉框)中的option

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏