innerHTML删除Internet Explorer中的属性引号 [英] innerHTML removes attribute quotes in Internet Explorer

查看:150
本文介绍了innerHTML删除Internet Explorer中的属性引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你在IE中获得DOM节点的innerHTML时,如果属性值中没有空格,IE将删除它周围的引号,如下所示:

When you get the innerHTML of a DOM node in IE, if there are no spaces in an attribute value, IE will remove the quotes around it, as demonstrated below:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <div id="div1"><div id="div2"></div></div>
        <script type="text/javascript">
            alert(document.getElementById("div1").innerHTML);
        </script>
    </body>
</html>

在IE中,警报将显示为:

In IE, the alert will read:

<DIV id=div2></DIV>

这是一个问题,因为我将此传递给需要有效XHTML的处理器,所有必须引用属性值。有没有人知道在IE中解决这种行为的简单方法?

This is a problem, because I am passing this on to a processor that requires valid XHTML, and all attribute values must be quoted. Does anyone know of an easy way to work around this behavior in IE?

推荐答案

IE innerHTML确实很烦人。我为它写了这个函数,这可能有帮助吗?它引用属性并将标记名设置为小写。顺便说一下,为了让它更烦人,IE的innerHTML不会删除非标准属性的引号。

IE innerHTML is very annoying indeed. I wrote this function for it, which may be helpfull? It quotes attributes and sets tagnames to lowercase. By the way, to make it even more annoying, IE's innerHTML doesn't remove quotes from non standard attributes.

根据评论进行编辑
该函数现在处理属性值中的更多字符,并可选择将属性值转换为小写。这个功能现在看起来更难看了~~)。如果要在等式中添加或删除字符,请编辑 [a-zA-Z \.\:\ [\] _ \(\)\& \\ \\ $ \%#\ @ \!0-9] + [?\s + |?>] 部分正则表达式。

function ieInnerHTML(obj, convertToLowerCase) {
    var zz = obj.innerHTML ? String(obj.innerHTML) : obj
       ,z  = zz.match(/(<.+[^>])/g);    

    if (z) {
     for ( var i=0;i<z.length;(i=i+1) ){
      var y
         ,zSaved = z[i]
         ,attrRE = /\=[a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+[?\s+|?>]/g
      ;

      z[i] = z[i]
              .replace(/([<|<\/].+?\w+).+[^>]/,
                 function(a){return a.toLowerCase();
               });
      y = z[i].match(attrRE);

      if (y){
        var j   = 0
           ,len = y.length
        while(j<len){
          var replaceRE = 
               /(\=)([a-zA-Z\.\:\[\]_\(\)\&\$\%#\@\!0-9\/]+)?([\s+|?>])/g
             ,replacer  = function(){
                  var args = Array.prototype.slice.call(arguments);
                  return '="'+(convertToLowerCase 
                          ? args[2].toLowerCase() 
                          : args[2])+'"'+args[3];
                };
          z[i] = z[i].replace(y[j],y[j].replace(replaceRE,replacer));
          j+=1;
        }
       }
       zz = zz.replace(zSaved,z[i]);
     }
   }
  return zz;
}

应该有效的键值对示例

data-mydata=return[somevalue] => data-mydata="return[somevalue]"
id=DEBUGGED:true => id="DEBUGGED:true" (or id="debugged:true" if you use the convertToLowerCase parameter)
someAttribute=Any.Thing.Goes => someAttribute="Any.Thing.Goes"

这篇关于innerHTML删除Internet Explorer中的属性引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆