zoukankan      html  css  js  c++  java
  • setAttribute()方法

    setAttribute(string name, string value):增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。

    1、样式问题
    setAttribute(class, value)中class是指改变class这个属性,所以要带引号。
      vName代表对样式赋值。
      例如:
      var input = document.createElement(input);
      input.setAttribute(type, text);
      input.setAttribute(name, q);
      input.setAttribute(class,bordercss);
      输出时:,即,input控件具有bordercss样式属性
    注意:class属性在W3C DOM中扮演着很重要的角色,但由于浏览器差异性仍然存在。
    使用setAttribute(class, vName)语句动态设置Element的class属性在firefox中是行的通的,但在IE中却不行。因为使用IE内核的浏览器不认识class,要改用className;
    同样,firefox 也不认识className。所以常用的方法是二者兼备:

    element.setAttribute(class, value);  //for firefox
    element.setAttribute(className, value);  //for IE
    2、方法属性等问题
    例如:
    var bar = document.getElementById(testbt);
    bar.setAttribute(onclick, javascript:alert('This is a test!'););
    这里利用setAttribute指定e的onclick属性,简单,很好理解。
    但是IE不支持,IE并不是不支持setAttribute这个函数,而是不支持用setAttribute设置某些属性,例如对象属性、集合属性、事件属性,也就是说用setAttribute设置style和onclick这些属性在IE中是行不通的。

    为达到兼容各种浏览器的效果,可以用点符号法来设置Element的对象属性、集合属性和事件属性。
    document.getElementById(testbt).className = bordercss;
    document.getElementById(testbt).style.cssText = color: #00f;;
    document.getElementById(testbt).style.color = #00f;
    document.getElementById(testbt).onclick= function () { alert(This is a test!); }

    由此延伸的问题:

    一个input的text,当将html赋值为某个div的innerHTML时,遇到一个现象,当在firefox下时(IE下不存在此问题), 赋值后的innerHTML里不含有value,即当你在文本框输入内容后,你想将赋值给div时,只会得到,这里总是会将value清除.

    这时,setAttribute起作用了,在input内加上:onkeyup=this.setAttribute('value',this.value),即动态的将input控件加上value值,这时再将文本框赋值给div,value将不会被清空

  • 相关阅读:
    JAVA嵌入运行Groovy脚本
    git撤销本地所有未提交的更改
    Java连接S3并上传Redis
    jython笔记
    Elasticsearch 5.2.x 使用 Head 插件连接不上集群
    elasticsearch 5.1 别的机器无法访问9200端口
    elasticsearch,http://ip:9200访问不到的解决办法
    在centos7中安装nodejs(npm )
    java标识符和关键字
    Java平台
  • 原文地址:https://www.cnblogs.com/dxsghr/p/6646222.html
Copyright © 2011-2022 走看看