【问题标题】:Find exact string in element jQuery在元素jQuery中查找确切的字符串
【发布时间】:2015-12-15 14:17:40
【问题描述】:

我在一个容器中有几个 span 元素,我想匹配其中一个 span 的确切单词以插入横幅。我不知道该怎么做。

首先我尝试了这个脚本:

$(document).ready(function(){
 if ($('.head.titlebox span').text().trim() === "match" ){
 $('<span class="myAwesomeBanner4"></span>').insertAfter(".productbox em.price.product-card-price")
 }
else if ($('.head.titlebox span').text().trim() === "matchother" ){
$('<span class="myAwesomeBanner5"></span>').insertAfter(".productbox em.price.product-card-price")
}
});

这不起作用 - 除非我删除它应该匹配的字符串:=== ""。所以这个脚本看起来很有效。不过,我无法将其与单词匹配-对我来说似乎是正确的,因此不确定为什么它不起作用。

然后我尝试了这个有效的脚本 - 但我不知道如何将其转换为使用 if 语句并创建我的 div 以插入到 DOM 中,如上:

$('.head.titlebox span').filter(function(index) { 
return $(this).text() === "match";}).css("background", "black"); 

用于定位字符串的 HTML:

<div class="head titlebox">
 <span id="artid">text</span><h1 id="prod-title">text</h1>
 <span>text</span><span>text</span>
 <span>match</span>
</div>

那么为什么第一个不工作 - 我如何将它与第二个脚本的工作过滤功能结合起来?

【问题讨论】:

  • 你需要使用each来遍历所有元素
  • 您想只插入一个横幅,还是同时插入两个?
  • 对 - .text() 返回选择器匹配的第一个元素的文本。

标签: javascript jquery html


【解决方案1】:

你需要遍历所有的span标签,

$('.head.titlebox span').each(function() {
   if ($(this).text() == "match") {
      //insert your html.
   }
})

【讨论】:

  • 请用“===”代替“==”
  • 啊。谢谢!有道理:p
  • 另外,Javascript 提供了 .match() 方法来比较字符串。可能是better alternative 使用:)
【解决方案2】:

试试这个:

$(".head").on("click", function() {
  var spanList = $(".head span");
  $.each(spanList,function(span){
      console.log($(spanList[span]).text());
      if($(spanList[span]).text() === "match"){
      	console.log("Matched")
      }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="head titlebox">
  <span id="artid">text</span>
  <h1 id="prod-title">text</h1>
  <span>text</span><span>text</span>
  <span>match</span>
</div>

【讨论】:

    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多