如果您只想唯一标识 DOM 中的某个元素,并能够在将来返回到同一个 DOM 元素,那么只需直接保存对该元素的引用即可。您不必通过一些从文档开头开始计数的奇怪选择器来获取元素,您只需保存对实际元素的引用即可。例如:
var lastClickedItem;
$("div").click(function() {
if (lastClickedItem) {
$(lastClickedItem).removeClass("clicked");
// do other things to the last clicked item
}
$(this).addClass("clicked");
lastClickedItem = this;
});
此代码将 lastClickedItem 保存在全局变量中。您甚至不必将其保存在全局变量中。您只需给它一个唯一的 ID 或类名,就可以使用它检索给定的元素。从 DOM 的前面开始计数返回到同一个元素似乎效率很低。
If you just want to uniquely identify an element in the DOM and be able to get back to the same DOM element in the future, then just save the reference to the element directly. You don't have to get an element back via some odd selector that counts from the beginning of the document, you can just save the reference to the actual element. For example:
var lastClickedItem;
$("div").click(function() {
if (lastClickedItem) {
$(lastClickedItem).removeClass("clicked");
// do other things to the last clicked item
}
$(this).addClass("clicked");
lastClickedItem = this;
});
This code saves the lastClickedItem in a global variable. You wouldn't even have to save it in a global variable. You could just give it a unique ID or class name and be able to retrieve the given element using that. Counting from the front of the DOM to get back to the same element seems pretty inefficient.
发布评论
评论(2)
我猜你正在寻找通用选择器 *
I guess you are looking for the universal-selector *
如果您只想唯一标识 DOM 中的某个元素,并能够在将来返回到同一个 DOM 元素,那么只需直接保存对该元素的引用即可。您不必通过一些从文档开头开始计数的奇怪选择器来获取元素,您只需保存对实际元素的引用即可。例如:
此代码将 lastClickedItem 保存在全局变量中。您甚至不必将其保存在全局变量中。您只需给它一个唯一的 ID 或类名,就可以使用它检索给定的元素。从 DOM 的前面开始计数返回到同一个元素似乎效率很低。
或者,使用唯一的类名:
If you just want to uniquely identify an element in the DOM and be able to get back to the same DOM element in the future, then just save the reference to the element directly. You don't have to get an element back via some odd selector that counts from the beginning of the document, you can just save the reference to the actual element. For example:
This code saves the lastClickedItem in a global variable. You wouldn't even have to save it in a global variable. You could just give it a unique ID or class name and be able to retrieve the given element using that. Counting from the front of the DOM to get back to the same element seems pretty inefficient.
Or, using a unique class name: