如何检测.title-bar下含Cheese的h1并为指定元素添加跳转点击事件?
Corrected jQuery Code for Your Requirement
Let's walk through fixing your code and breaking down the key issues that were preventing it from working as intended:
Issues in Your Original Code:
- The
.contains()method was misused—it's not a chainable selector method here. Instead, we need to check the text content of the targeth1directly. window.location.hrefis a property, not a function, so you assign the URL to it rather than calling it like a method.- There was no conditional check to only apply the click event if the "Cheese" word is actually present in the
h1.
Corrected Code:
jQuery(document).ready(function($) { // Check if the h1 inside .title-bar contains the word "Cheese" const titleHasCheese = $('.title-bar h1').text().trim().includes('Cheese'); if (titleHasCheese) { // Attach click event to the target span element $('span.xoo-cp-close.xoo-cp-icon-cross').on('click', function() { window.location.href = 'https://abcx.com/cheese'; // Use full valid URL }); } });
Key Details Explained:
- DOM Ready Wrapper: Using
jQuery(document).ready(function($) { ... })ensures the code runs only after all page elements are loaded. The$parameter lets us use jQuery's shorthand inside the function for cleaner code. - Text Content Check:
$('.title-bar h1').text().trim().includes('Cheese')grabs the text of theh1, removes extra whitespace, and checks if it contains the substring "Cheese". This is case-sensitive—if you want to match any case (like "cheese" or "CHEESE"), use.toLowerCase().includes('cheese')instead. - Click Event Attachment: Using
.on('click', function() { ... })is the recommended jQuery way to add event handlers (instead of setting theonClickattribute directly, which is less flexible). - Valid URL: Adding
https://to the URL ensures it's treated as an absolute address, avoiding unexpected relative path behavior.
Optional Case-Insensitive Version:
If you need to match "Cheese" regardless of capitalization:
jQuery(document).ready(function($) { const titleHasCheese = $('.title-bar h1').text().trim().toLowerCase().includes('cheese'); if (titleHasCheese) { $('span.xoo-cp-close.xoo-cp-icon-cross').on('click', function() { window.location.href = 'https://abcx.com/cheese'; }); } });
内容的提问来源于stack exchange,提问作者Arc
相关产品推荐
相关产品推荐

