使用jQuery/JS ES5筛选不含*-zoneid="10"数据属性的横幅元素
To target the banner elements that don’t have any attribute matching the pattern data-[random-string]-zoneid="10", you’ll need to combine jQuery’s filtering with a check for attribute names that fit that dynamic pattern. Here’s how to make it work:
Step-by-Step Breakdown
- Grab all banner elements: Start by selecting all your banner elements using their shared class or parent container (replace
.bannerwith your actual selector, like#banner-wrapper > div). - Filter out unwanted elements: Use jQuery’s
.filter()method to loop through each banner and exclude any that have an attribute starting withdata-and ending with-zoneid—regardless of the random string in between.
Working Code Example
// Replace .banner with your actual banner selector const targetBanners = $('.banner').filter(function() { // Iterate through every attribute on the current element for (const attr of this.attributes) { // Check if the attribute name matches the dynamic pattern if (attr.name.startsWith('data-') && attr.name.endsWith('-zoneid')) { // If it matches, exclude this element from the result set return false; } } // No matching attribute found—keep this element return true; }); // Now perform your后续操作 on the filtered banners targetBanners.hide(); // Example action: hide the selected banners
Optional: Add Value Check for Extra Precision
If you want to ensure you’re only excluding elements where the attribute’s value is exactly "10", tweak the condition:
const targetBanners = $('.banner').filter(function() { for (const attr of this.attributes) { if (attr.name.startsWith('data-') && attr.name.endsWith('-zoneid') && attr.value === '10') { return false; } } return true; });
Why This Works
Since the attribute name has a random string in the middle, standard jQuery attribute selectors won’t work. By directly inspecting each element’s attributes, we can reliably spot and exclude the banners with that dynamic attribute—no need to modify the injected HTML or rely on fixed class names/values.
内容的提问来源于stack exchange,提问作者kruzyk

