【问题标题】:Get all attributes of element is working different on IE获取元素的所有属性在 IE 上的工作方式不同
【发布时间】:2011-11-26 23:21:12
【问题描述】:

如果您在 IE7 和 firefox 上运行此脚本 http://jsfiddle.net/y8jp8/2/,您可以看到: 结果不一样。

我只想查看 3 个属性(id、title 和 myattr)及其值。如何在 IE 中执行此操作?

【问题讨论】:

  • 每个 ID 元素 ... ID 不应该只有一个和一个吗?
  • @roXon 嗯?每个 ID 元素? OP在哪里说的?
  • 我误解了Q.探索。

标签: jquery


【解决方案1】:

这是对 roXon 答案的更正,但仍然没有完美的解决方案..

var result = "";
var attrs = $("#sample")[0].attributes;

for(var i=0;i<attrs.length;i++) {
    if(attrs[i].nodeValue != null 
    && attrs[i].nodeValue != '' 
    && attrs[i].nodeValue != 'inherit'){
        result += ( attrs[i].nodeName + "=" + attrs[i].nodeValue + "<br>");
    }

    $('#log').html(result);
}

http://jsfiddle.net/digitaloutback/pMVJw/9/

更新:

IE7 似乎没有过滤掉未指定的属性,例如,这是您示例中“sample”属性的数据:

parentNode => null 
nodeValue => sample 
firstChild => null 
name => id 
expando => false 
lastChild => null 
ownerDocument => [object] 
attributes => null 
previousSibling => null 
value => sample 
nodeType => 2 
nodeName => id 
childNodes => null 
nextSibling => null 
specified => true 
ownerElement => undefined 

因此,您需要针对“指定”进行测试,例如:

var result = "";
var attrs = $("#sample")[0].attributes;

for(var i=0;i<attrs.length;i++) {   

    if(attrs[i].specified === true ) {
        result += ( attrs[i].nodeName + "=" + attrs[i].nodeValue + "<br>");
    }

    $('#log').html(result);

}

http://jsfiddle.net/digitaloutback/pMVJw/10/

【讨论】:

  • 如果我清空我的属性,此解决方案将不起作用:&lt;div id="sample" title="" myattr=""&gt;&lt;/div&gt; 我仍然想列出 3 个属性。
【解决方案2】:

有什么理由不能只获得所需的三个显式值而不是遍历所有属性?这让我在 IE7 和 Chrome 中得到相同的结果。

http://jsfiddle.net/y8jp8/22/

var result = "";
result += 'id=' + $('#sample').attr('id') + '<br />';
result += 'title=' + $('#sample').attr('title') + '<br />';
result += 'myattr=' + $('#sample').attr('myattr') + '<br />';
$("#log").html( result );

【讨论】:

  • 在我的应用程序中,我存储了许多元素属性的值。这些属性计数可能会有所不同。我知道,如果我用前缀 data- (在 html5 上)更改这些属性名称,我可以很容易地使用 jQuery 数据方法 stackoverflow.com/questions/999535/…>
  • 在将我的代码更改为 jQuery 数据方法之前,我可以使用此代码。但是,这不是一个完美的解决方案。
猜你喜欢
  • 2021-04-17
  • 1970-01-01
  • 2013-11-04
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 2017-11-16
相关资源
最近更新 更多