zoukankan      html  css  js  c++  java
  • 动态地添加HTML控件-JavaScript基础

    相关:

    document对象的createElement()方法可以创建一个新的HTML控件(document.createElement("input");)

    setAttribute()方法设置控件类型、设置控件的名称(otext.setAttribute("type","text");otext.setAttribute("name","username");)。

    appendChild()方法将新的HTML控件插入到相应的元素的最后一个子节点后面( document.form.appendChild(obtn);)。

     document.form.innerHTML = ""; 将内容设为空

    1、示例代码

    <!DOCYTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>动态添加html控件</title>
    <style>
    body{font-size: 12px}
    .button{background-color: #03a9f4;color: white}
    </style>
    </head>
    <body>
    <form name="form">
      <input type="button" class="button" value="添加文本框" onclick="addText()">
      <input type="button" class="button" value="添加按钮" onclick="addBtn()">
      <input type="button" class="button" value="删除所有控件" onclick="delElement()">
      <br><br>用户名:
    </form>
    </body>
    <script>
    function addText() {
      var otext = document.createElement("input");//创建input控件
      otext.setAttribute("type","text");//设置控件类型
      otext.setAttribute("name","username");//设置控件名称
      document.form.appendChild(otext);//将控件添加到form节点子节点后面
    }
    function addBtn() {
      var obtn = document.createElement("input");
      obtn.type = "button";//设置类型为button
      obtn.value = "确定";//设置控件显示的文字
      document.form.appendChild(obtn);//将控件添加到form节点子节点后面

    }
    function delElement() {
      document.form.innerHTML = "";//清空了所在页面
    }
    </script>
    </html>

    2、示例效果图

    源码下载:动态添加HTML控件.zip

  • 相关阅读:
    js 跳转链接的几种方式
    js 指定分隔符连接数组元素join()
    Ajax async属性
    非负数正则表达式
    firefox因 HTTP 严格传输安全(HSTS)机制无法打开网页
    查看linux系统某宏的定义(另类)
    ctags高级用法
    ctags简明用法
    关于数组和指针的一道例题的解读
    让gcc和gdb支持intel格式的汇编
  • 原文地址:https://www.cnblogs.com/qikeyishu/p/7603549.html
Copyright © 2011-2022 走看看