jQuery 循环遍历两个 DIV 中的元素
我有一个脚本,它循环遍历 DOM 元素列表并在找到它们时对其进行操作。我遇到的问题是我需要在两个不同的 div 中搜索相同的元素。
这是我到目前为止所拥有的
var elements = {
1 : "h1",
2 : "h2",
3 : "h3",
4 : "h4",
5 : "p",
6 : "li",
7 : "a",
8 : "td",
9 : "span",
10 : "img"
}
$.each(elements, function(key, val){
if(val != "img") {
if($(".t_content " + val + ":not([id^=element])"))
$(".t_content " + val + "[id^=element]").addClass('t_element');
} else {
$('.t_content, .t_component').find('img, div > img').addClass('t_element edit_img_area').removeClass('yellow');
$(val).unwrap('a');
}
});
我当前搜索的 div 是 $(".t_content")
但我想搜索 .t_content
和 .t_component
code>... 我知道您可以像这样搜索 $(".t_content, .t_component")
但我不知道如何将其合并到此脚本中。
感谢您的帮助!
I have a script that loops through a list of DOM elements and manipulates each as it finds them. The problem I am running into is that I need to search two different divs for the same elements.
This is what I have so far
var elements = {
1 : "h1",
2 : "h2",
3 : "h3",
4 : "h4",
5 : "p",
6 : "li",
7 : "a",
8 : "td",
9 : "span",
10 : "img"
}
$.each(elements, function(key, val){
if(val != "img") {
if($(".t_content " + val + ":not([id^=element])"))
$(".t_content " + val + "[id^=element]").addClass('t_element');
} else {
$('.t_content, .t_component').find('img, div > img').addClass('t_element edit_img_area').removeClass('yellow');
$(val).unwrap('a');
}
});
The div I am searching currently is $(".t_content")
but I want to search .t_content
and .t_component
... I know you can search like this $(".t_content, .t_component")
but I don't know how to incorporate that into this script.
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无需循环,只需一次选择所有元素即可:
No need to loop, just select all the elements at once:
为什么不做这样的事情:
您可以将第二个参数(上下文)传递给 jQuery 中的 $() ,告诉它在上下文中查找选择器中的项目。在您的情况下,您的第二个参数将是您要在其中搜索的两个 div:
$(".t_content, .t_component")
。Why don't you do something like this:
You can pass a second argument (context) to $() in jQuery which tells it to look within the context for the items you have in your selector. In your case, your second argument will be the two divs you want to search within:
$(".t_content, .t_component")
.您可以这样做:
或者,另一种方式,如果您将项目存储在一个简单的数组中,您可以这样做:
在第一个示例中,我为您保存
$elements
,以使其更加干燥,因为您可以只重用这一块,如果您想在其他地方使用它,它会更快,因为元素现在缓存在 jQuery 中。以下是如何循环遍历 JSON:
我将其放入一个数组中,因为它看起来不需要查看键和值,您只需要一个要检查的元素数组。
You could do something like this:
Or, another way, if you store your items just in a simple array you could do:
In the first example im saving
$elements
for you to keep it more DRY since you can just reuse that one piece, and it'll be faster if you want to use it elsewhere since the elements are now cached in jQuery.Here is how to loop through the JSON:
I put it in an array though becuse it doesnt look like you need to see the key and value, you just want a, well, array of elements to check through.