[英]If statement does not seem to be working properly
我在一個房地產網站上工作,並希望有特定的頁面來顯示出租/出售的房產。 我試圖只顯示具有“租金”狀態的屬性,但 if 語句似乎只是默認為 else。
使用邊框 styles 可見查看 if 語句。
web 頁面: http://targetrealtygroupdev.com/rent/
我錯過了什么?
<div class="property-item">
<div class="proprty-inner>
<div class="property-status-bg">
"Rent"
</div>
</div>
</div>
.one {
border: 1px solid red;
}
.two {
border: 1px solid blue;
}
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var status = document.getElementsByClassName("property-status-bg");
for (item of status) {
var type = item.innerText;
if (type == 'Rent') {
jQuery('.property-item').addClass('one');
} else {
jQuery('.property-item').addClass('two');
}
}
});
</script>
您正在更改每個項目的所有jQuery('.property-item')
並且.property-status-bg
不僅帶有簡單的文本 == 'Rent' 或 'Sale'...
它看起來像:
<p>
<span class="property-status-bg" style="background-color: #888">
Rent
<span class="property-arrow" style="border-left-color: #888; border-right-color: #888"></span>
</span>
</p>
所以你必須使用string.include方法
嘗試:
document.addEventListener("DOMContentLoaded", function(event)
{
document.querySelectorAll('.property-status-bg').forEach(item =>
{
let ClassChoice = item.textContent.includes('Rent') ? 'one' : 'two'
item.closest('.property-item').classList.add( ClassChoice )
})
})
您正在選擇所有元素,而不是選擇您在循環中引用的元素。
item.closest('.property-item').classList.add('one');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.