匹配div中的部分文本,如果匹配另一个div中的文本,则显示跨度-jQuery和JavaScript [英] Match partial text in a div and if it matches text in another div then show a span - jquery and javascript
问题描述
如果有缺货消息,我需要显示产品的库存数量:
I need to show the quantity in stock of a product if there is an out of stock message for it:
<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,但是它仅适用于完全匹配的文本,而不适用于部分匹配的文本:
I tried this jQuery however it only works with an exact text match and not with a partial text match:
if ( $(".OutOfStockMessage").text() == $(".ItemDecription").text() ) {
$(".Quantity").show();
}
这是小提琴: https://jsfiddle.net/8jmpnwuy/
如果.OutOfStockMessage包含单词'Avocado'和其他单词,那么我需要在div内包含该单词'Avocado'的span来显示.
When .OutOfStockMessage contains the word 'Avocado' plus other words then I need the span inside of the div which contains the word 'Avocado' to show.
推荐答案
您可以使用.filter()
函数查找带有部分文本与OutOfStockMessage消息文本匹配的所有itemdescription div.
You can use .filter()
function to find all itemdescription divs with partial text matching OutOfStockMessage message text.
然后您可以在这些集合中找到立即跨度元素并显示它们.我建议使用类选择器而不是直接子选择器.这样可以减少因DOM更改而引起的错误
You can then find the immediate span elements in these sets and show them. I would suggest using a class selector instead of immediate child selector. This makes it less error prone to DOM changes
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
这篇关于匹配div中的部分文本,如果匹配另一个div中的文本,则显示跨度-jQuery和JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!