如果元素包含(关键字),请执行某些操作

时间:2018-08-15 20:06:14

标签: jquery

我有这段代码,我试图首先在div中获取内容,然后将其与字符串匹配。如果匹配...做点什么。但是,此代码似乎与一切匹配。

逻辑是这样的: 1.对于四个页脚节 2.如果该部分的标题与“保持联系”相匹配 3.添加此图片

在此先感谢您的帮助!

// ADD ARROW TO FOOTER
  $(".footer-nav__title").each(function () {

     var results = $( ".footer-nav__title" ).html();
     var match = ("Stay Connected");  

     if($('results:contains(match)')) {
          $(this).append('<img src="https://cdn.shopify.com/s/files/1/0013/8467/7443/files/footer-arrow.png?8377676856849539925" alt="" class="footer-arrow" />');
     } 

   });

2 个答案:

答案 0 :(得分:5)

结果 match 都是字符串变量,但是您没有在代码中正确连接它们。即使您这样做,也不会获得理想的效果。

这应该为您提供所需的结果:

var results = $(this).html();
var match = ("Stay Connected");  

if (results.indexOf(match) > -1) {
      $(this).append('<img src="https://cdn.shopify.com/s/files/1/0013/8467/7443/files/footer-arrow.png?8377676856849539925" alt="" class="footer-arrow" />');
} 

答案 1 :(得分:3)

/* Criteria from the OP
   1. For each of the four footer sections
   2. If the title of the section matches "Stay Connected"
   3. Add this image
*/

//#1
$(".footer-nav__title").each(function(){
  //#2
  //Don't look up the element again, especially a global selector that will get them
  //all.  Use the one you are looping over.
  if (this.innerHTML.indexOf('Stay Connected') > -1) {
    //#3
    $(this).append('<img src="https://cdn.shopify.com/s/files/1/0013/8467/7443/files/footer-arrow.png?8377676856849539925" alt="" class="footer-arrow" />');
  }
});

相关问题