You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测.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 target h1 directly.
  • window.location.href is 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 the h1, 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 the onClick attribute 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:38:55