且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Jquery匹配具有相同id/class的多个元素

更新时间:2021-12-08 10:25:17

你需要使用each() 遍历匹配的元素.不要为多个元素使用相同的 id,而是使用相同的类,因为元素的 id 应该是唯一的.要选择具有相同类的多个元素,您可以使用像 $('[id=container]') 这样的属性选择器,但***使用类并保持元素的 id 唯一.

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.

现场演示

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);