繁体   English   中英

基于另一个文本类内容的JavaScript URL重定向

[英]JavaScript url redirect based on another text class content

我正在基于过滤下面显示的h2类中的内容来创建jQuery url重定向。 到目前为止,我一直在尝试测试您在下面看到的内容:

我需要帮助的是对h2进行过滤以查找某个单词。 例如,如果h2类包含单词“ Unit”,则单击链接将重定向到新的网页,在本例中为www.link.com。 否则,如果没有,它将与href中已有的默认url.com保持在一起。

<h2 class="unit"> Sample Unit </h2>

<a "href="http://www.url.com" target="_blank"> Sample Link </a>

我已经在下面的jQuery中看到了此解决方案,但是我无法对其进行过滤或编辑以正确过滤h2。

$(location).attr('href', 'http://www.link.com')

如果您正在谈论h2 innerHTML,请尝试这一

 var str = document.getElementsByClassName("unit")[0].innerHTML; var result = str.indexOf("Unit") > -1; (result) ? $("a").attr("href", "http://www.link.com/"): $("a").attr("href", "http://www.url.com"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2 class="unit"> Sample Unit </h2> <a href="http://www.url.com" target="_blank"> Sample Link </a> 

使用jquery's .contains检查h2包含Unit ,如下所示:

var hasUnit=$('h2').contains('Unit'); //returns true or false

根据上述返回值更改href

    /* get all "h2" tags with class "unit"
    and loop on each elements it finds in your page */

    $("h2.unit").each(function() {

      /* check each h2.unit if it has "unit" text inside it
      we internally changed to lowercase to make it case insensitive
      if "unit" text does not exists .indexOf("unit") will return -1 */

        if ($(this).html().toLowerCase().indexOf("unit") >= 0) {

          // change its next sibling with "a" tag's href to www.link.com

          $(this).next("a").attr("href", "http://www.link.com");
      }
    });

评论之一建议的快捷方式。

$("h2.unit:contains('unit')").next("a").attr("href", "http://www.link.com");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM