如果在页面中找到单词 'Cheese',则 jQuery 更改 windows.location.href 目录的代码

jQuery code that changed the windows.location.href directory if the word 'Cheese' found in the page

如何在 div 中搜索 h1 元素,其中 class .title-bar 包含单词 "Cheese"? 如果找到奶酪,则添加一个点击事件以重定向到 abcx。com/cheese。

这是我目前尝试过的方法:

jQuery(document).ready(function(jQuery){
    jQuery("span.xoo-cp-close.xoo-cp-icon-cross")
        .contains('.title-bar h1' "Cheese")
        .attr( "onClick", "window.location.href('abcx.com/cheese')" );
});

感谢帮助,干杯

假设您的 html 标记如下所示..

<span class="xoo-cp-close xoo-cp-icon-cross">
  <div class="title-bar">
    <h1>Cheese</h1>
  </div>
</span>

您可以像这样简单地迭代 document ready 上的所有 h1 ..

jQuery(document).ready(function() {
  jQuery(".title-bar h1", "span.xoo-cp-close.xoo-cp-icon-cross").each(function() {
    var $h1 = jQuery(this),
      h1Text = $h1.text().trim().toLowerCase();

    if (h1Text.indexOf("cheese") > -1) {
      $h1.attr("onClick", "window.location.href('abcx.com/cheese')");
    }
  });
});

上面的代码迭代了一个元素内的所有 h1,其中 class .title-bar 是包含 class [=14= 的 span 元素的后代] 和 xoo-cp-icon-cross