javascript Jquery匹配具有相同id/class的多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17498464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery matching multiple elements with same id/class
提问by David Garcia
I am working on showing a message when a particular element has a width of less than 50, however there are multiple elements with the same class and only the first element in the page is displaying the message. here is the jsfiddle http://jsfiddle.net/MaNdn/23/
我正在处理当特定元素的宽度小于 50 时显示消息,但是有多个元素具有相同的类,并且只有页面中的第一个元素显示消息。这是 jsfiddle http://jsfiddle.net/MaNdn/23/
Here is the function.
这是功能。
function checkads() {
if ($('#container').height() < 50) {
$('#container').parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
//
}
}
$(document).ready(checkads);
My question is, how do you make the message prepend to all element id instances found. I have various advertisements around my website, they are all wrapped in an div element named advertisement_container
then how do I match them all at once
我的问题是,如何将消息添加到找到的所有元素 id 实例之前。我的网站上有各种广告,它们都包裹在一个名为 div 的元素中,advertisement_container
那么我如何一次匹配它们
回答by Adil
You need to use each()to iterate through the matched element. Instead of using same id for multiple elements use the same class as the id of element is supposed to be unique. To select multiple elements with same class you can use attribute selector like $('[id=container]') but it is better to use class and keep the ids of elements unique.
您需要使用each()来遍历匹配的元素。不要对多个元素使用相同的 id,而是使用相同的类,因为元素的 id应该是唯一的。要选择具有相同类的多个元素,您可以使用像 $('[id=container]') 这样的属性选择器,但最好使用 class 并保持元素的 id unique。
function checkads() {
$('.someclass').each(function(){
if($(this).height() < 50) {
$(this).parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
}
});
}
$(document).ready(checkads);
回答by Dan F
ID has to be unique. Change it to be a class, not an ID, then you can use filterand something like
ID 必须是唯一的。将其更改为一个类,而不是一个 ID,然后您可以使用过滤器之类的
function checkads() {
$('.container').filter(function (index) {
return $(this).height() < 50;
}).parent().parent().prepend('<div id="ad-notice">Please support our website</div>');
}