【问题标题】:Is there an actual use case that requires getAttributeNode and/or getAttributeNodeNS? [closed]是否存在需要 getAttributeNode 和/或 getAttributeNodeNS 的实际用例? [关闭]
【发布时间】:2011-06-03 15:15:45
【问题描述】:

有人能想到一个实际用例,我们将永远要求使用getAttributeNode 和/或getAttributeNodeNS

据我所知,getAttribute 和/或getAttributeNS 解决了所有用例,因此提出了这个问题。

【问题讨论】:

  • 那么,你会建议他们从语言中删除它吗?

标签: javascript web-services web-applications


【解决方案1】:

它可以让你以 Node 的形式获取 item,这是一个由其他 DOM 组件(如元素、处理指令、cmets 等)共享的接口,因此您可以将其与其他 item 类似地对待。不知道为什么,但你可以... :)

例如:

<button id="choose_attr">choose attribute node</button>
<button id="choose_text">choose text node</button>
<button id="getchosennodevalue">get chosen node's value</button>

<script>
var chosenNode;
document.getElementById('choose_attr').addEventListener('click', function (e) {
    chosenNode = e.target.getAttributeNode('id'); // Attribute node
}, false);
document.getElementById('choose_text').addEventListener('click', function (e) {
    chosenNode = e.target.firstChild; // Text node
}, false);

document.getElementById('getchosennodevalue').addEventListener('click', function () {
    alert(chosenNode.nodeValue); // We can get the value with a shared property, no matter if it is a text node, comment node, element, attribute node, etc.
}, false);
</script>

即使您只使用该变量来存储属性节点,人们可能更愿意将其预先构建到一个不同于其他类型(如字符串)的特殊对象中。

虽然您的问题是关于 getAttributeNode*,但就一般属性节点的使用而言,我认为使用 document.createAttribute 之类的可能会更方便,您可以在其中创建然后传递这样的节点来设置它稍后在一个元素上。但是获取现有属性确实似乎不太通用(尽管可以想象这样一种情况,即您在属性节点周围传递,有时在没有元素的情况下重新创建,有时从现有元素中检索 - 使用 getAttributeNode 可以避免构建您的拥有 getter 和 setter 的对象,并使用相同的接口处理它们)。

【讨论】:

  • 好吧,我不明白这个例子如何证明我们有getAttributeNode
  • 它只是演示了一种与节点类型无关的多态性——允许您方便地将属性节点与其他节点共同对待(尽管Node接口也有nodeType允许您区分节点就像你想要区分类型的其他节点的属性节点一样)。
【解决方案2】:

确实很少有理由使用getAttributeNode()。但是,我发现它在过去作为 Internet Explorer 的 getAttributesetAttribute 错误的解决方法很有用。例如,采用以下 HTML:

<div id="test" onclick="alert()">

以及以下代码:

var test = document.getElementById("test");
alert(typeof test.getAttribute("onclick"));

Internet Explorer 7 及更低版本将在警报中报告function,这与新版本和其他正确报告string 的浏览器不同。解决方法涉及getAttributeNode()

alert(typeof test.getAttributeNode("onclick").nodeValue);

在所有浏览器中正确输出string,尽管性能成本很小。同样的问题适用于可以通过属性设置的布尔值和其他非字符串属性。当然,如果 IE 没有这个错误,这将是不必要的,但它让我感谢 getAttribute() 的替代品。

我已经设置了一个示例供您测试和使用 — http://jsfiddle.net/PVjn5/。在 jQuery.com 上也有 a ticket I filed 关于它。

【讨论】:

    【解决方案3】:

    您将在需要将属性名称和值(以及命名空间,如果适用)封装在单个对象中的情况下使用它们。通过 JavaScript 操作 HTML 用户界面时这样做的用例可能很少见。但是,浏览器实现了DOM specification,并且必须提供这些方法以满足规范。当 DOM 不用于操作基于 HTML 的用户界面时,有很多用例。

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 1970-01-01
      • 2023-02-26
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2010-10-06
      相关资源
      最近更新 更多