如何使用JQuery根据文本值将不同的属性分配给同一类的多个元素



例如:

我有多个<span>元素,类为.listing-text,表示Available,有些表示Pending,还有一些表示Sold

我想将green背景分配给AvailableyellowPending以及redSold的背景。

我已经尝试了一些不同的循环之类的。到目前为止,我所能做的就是把每个框都变成绿色,我想这是因为我没有正确地迭代。我唯一能做对的就是

$('.listing-text').css('background-color','green');

它可靠地将所有背景更改为绿色。

如有任何帮助,我们将不胜感激。

参见注释:

// Get all the listings and loop over them
document.querySelectorAll(".listing-text").forEach(function(listing){
// Check the text of the span for the possible choices and
// apply the appropriate CSS class
switch (listing.textContent) {
case "Available":
listing.classList.add("available");
break;
case "Pending":
listing.classList.add("pending");
break;
case "Sold":
listing.classList.add("sold");
break;       
}
});
.available { background-color:green; }
.pending { background-color:yellow; }
.sold { background-color:red; }
<span class="listing-text">Available</span>
<span class="listing-text">Pending</span>
<span class="listing-text">Sold</span>
<span class="listing-text">Available</span>
<span class="listing-text">Pending</span>
<span class="listing-text">Sold</span>

看起来您无法编写与元素文本匹配的css选择器(https://stackoverflow.com/a/1520469/8755370)。

相反,您可以循环浏览整个列表集,并为每个类别添加另一个类。所以所有的都会有.listing-text,但有些会是.listing-available.listing-pending。从那里你可以编写你的jquery函数,就像你发布的一样。

使用jQuery的.each函数尝试以下操作。

$('.listing-text').each(function() {
let listText = $(this).text()
switch (listText) {
case 'Pending':
$(this).addClass('pending')
break
case 'Sold':
$(this).addClass('sold')
break
case 'Available':
default:
$(this).addClass('available')
break
}
})
.available {  background-color: green  }
.pending {  background-color: yellow  }
.sold {  background-color: red  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="listing-text">Available</span>
<span class="listing-text">Sold</span>
<span class="listing-text">Pending</span>

我在这里所做的是在每个列出的文本元素上循环,获取文本,并根据其文本值应用一个类。

最新更新