根据 the spec , language 继承自具有 lang
集的最近的祖先元素。那么我如何获得这些后代之一的语言呢?
我正在使用 lang
属性设置语言:
<div id="outer" lang="es">
<div id="inner">¿Por qué?</div>
</div>
并尝试使用 lang
属性访问它:
alert(document.getElementById('outer').lang);
alert(document.getElementById('inner').lang);
我很快注意到内部 div 的 lang
属性不是继承的语言(或者它不是继承;不知道)。 This fiddle展示了我所看到的行为。
如何使用 Javascript 确定元素的语言?我真的很想利用 lang
属性的继承,因为我也需要它来使用屏幕阅读器。
最佳答案
根据您链接到的规范:
To determine the language of a node, user agents must look at the nearest ancestor element (including the element itself if the node is an element) that has a
lang
attribute in the XML namespace set or is an HTML element and has alang
in no namespace attribute set. That attribute specifies the language of the node (regardless of its value).
从另一个元素继承并不意味着为元素本身设置属性。因此,您的代码还必须找到具有 lang
属性(如果存在)的最近父级。参见 this question如果这听起来有问题。
关于javascript - 如何使用 Javascript 确定元素的语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28463179/