【问题标题】:Match partial text in a div and if it matches text in another div then show a span - jquery and javascript匹配 div 中的部分文本,如果它匹配另一个 div 中的文本,则显示一个 span - jquery 和 javascript
【发布时间】:2020-05-11 06:18:05
【问题描述】:

如果产品有缺货消息,我需要显示该产品的库存数量:

<div class="OutOfStockMessage">Sorry, Avocado is not available in the quantity that you selected. Please select a lower quantity to be able to place this order.</div>
<div class="ItemDecription">Avocado<span class="Quantity" style="display:none"> 16 pieces in stock</span></div>
<div class="ItemDecription">Tomato<span class="Quantity" style="display:none"> 97 pieces in stock</span></div>
<div class="ItemDecription">Mushroom<span class="Quantity" style="display:none"> 217 pieces in stock</span></div>

我尝试了这个 jQuery,但它只适用于精确文本匹配,而不适用于部分文本匹配:

if ( $(".OutOfStockMessage").text() == $(".ItemDecription").text() ) {
$(".Quantity").show();
}

这里是小提琴:https://jsfiddle.net/8jmpnwuy/

当 .OutOfStockMessage 包含单词“Avocado”和其他单词时,我需要显示包含单词“Avocado”的 div 内的 span。

【问题讨论】:

    标签: jquery text match partial


    【解决方案1】:

    您可以使用.filter() 函数查找所有带有部分文本匹配 OutOfStockMessage 消息文本的 itemdescription div。

    然后您可以在这些集合中找到直接的 span 元素并显示它们。我建议使用类选择器而不是直接子选择器。这使得 DOM 更改更不容易出错

    var stockMessageTxt= $(".OutOfStockMessage").text();
    var $itemDescrptnToShow = $(".ItemDecription").filter(function(){
      return stockMessageTxt.includes($(this).clone()
        .children() //select all the children
        .remove()   //remove all the children
        .end()  //again go back to selected element
       .text());
    });
    $('.Quantity', $itemDescrptnToShow).show();
    

    Working Demo

    【讨论】:

    • 谢谢。言语无法形容我对您的帮助的感激之情。您的答案和代码将用于我的电子商务网站,每天帮助数百人。
    • @AlexTheDude :很高兴它有帮助:)
    • 好的,我犯了一个错误,以为我的电子商务平台在 .ItemDescription div 中有 .Quantity 跨度,但跨度实际上是在 div 之后而不是在其中。这会抛出工作代码,我尝试了几个小时让它工作但没有任何运气。我将添加一个指向小提琴的链接,显示它的实际情况。
    • @AlexTheDude:嗨,Alex,随着 DOM/HTML 的更改,您可以将其作为新问题发布吗?使用正确缩进的 HTML?将发布答案。
    • 是的,我将把它作为一个带有正确缩进 HTML 的新问题发布。我将开始处理新问题,并应在几分钟内发布。谢谢。
    猜你喜欢
    • 2021-09-30
    • 2012-01-28
    • 2011-10-04
    • 2017-09-08
    • 2021-09-24
    • 1970-01-01
    • 2020-10-28
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多