我们可以假设 .product 在整个页面中是唯一的。我们可以使用 id 而不是 class,但在这种情况下,我们选择了 class 属性。
最佳答案
We may assume that .product is unique throughout the page.
就性能而言,最佳 当然是 ID 选择器,但由于您使用的是类,.product会排在第二位。
至于可维护性、可读性和语义(还有更多关于性能的内容)...
.product意味着
Find any elements that have a class product.
非常容易理解,如果您基于上述假设使用它,几乎与 ID 选择器相同。
我想在这种情况下使用类选择器和 ID 选择器之间的唯一区别是 ID 选择器强制此元素的唯一性,而不仅仅是因为 碰巧 有一个这样的元素.换句话说,ID 选择器根据文档将只有一个这样的唯一元素的知识来操作,而类选择器则没有。
.main .category .product意味着
Find any elements that have a class product
which are contained in any elements that have a class category
which are contained in any elements that have a class main.
Find only <div> elements that have a class product
which are contained in only <div> elements that have a class category
which are contained in only <div> elements that have a class main.