There are loads of basic, native JavaScript methods that many developers don't know about. Many people don't know about the Element.classList API, for example, so className
management becomes another case for needing a JavaScript toolkit for even the most basic tasks. Another case is checking for node parenting -- developers believe it requires a toolkit or a loop checking parentNode
up the chain; no so! Nodes provide a contains
method to check if one node if a parent of another:
许多开发人员不了解许多基本的本机JavaScript方法。 例如,许多人不了解Element.classList API,因此className
管理成为需要JavaScript工具包来完成最基本任务的另一种情况。 另一种情况是检查节点的育儿状态–开发人员认为它需要一个工具包或一个循环来检查链上的parentNode
; 不行! 节点提供了一个contains
方法,用于检查一个节点是否为另一节点的父节点:
function(parentNode, childNode) {
if('contains' in parentNode) {
return parentNode.contains(childNode);
}
else {
return parentNode.compareDocumentPosition(childNode) % 16;
}
}
You'll note we check for the contains
method before using it, as you would probably expect, and use the rarely-known compareDocumentPosition
in the case that contains
isn't supported (Firefox < 9). This method would be helpful when creating a drag & drop widget and determining moves between lists. Anyways, before you jump to the conclusion that you need a toolkit for something that seems basic, do some quick research and hopefully you find an easier way!
您会注意到,正如您可能期望的那样,我们在使用之前检查了contains
方法,并在不支持contains
的情况下使用了鲜为人知的compareDocumentPosition
(Firefox <9)。 在创建拖放小部件并确定列表之间的移动时,此方法将非常有用。 无论如何,在得出结论认为您需要一个基本工具包的结论之前,请进行一些快速研究,并希望找到一种更简单的方法!