评论:我有一个带有状态的动态产品列表。该代码仅作用于第一个,而另一个则不会使“有货”颜色变为红色?
<body>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">Available</div>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">In Stock</div>
</body>
<script>
let element = document.getElementById('greenStock');
var textColor = element.innerHTML;
if (textColor === 'In Stock'){
element.style.color = "red";
}
</script>
</html>
答案 0 :(得分:1)
textColor
是元素的innerHTML
,属性style
仅存在于元素上,而不存在于元素的innerHTML
上。
这应该有效
<html>
<body>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">Available</div>
<div id="greenStock" class="zcd-status">In Stock</div>
<div id="greenStock" class="zcd-status">In Stock</div>
</body>
<script>
let element = document.getElementById('greenStock');
var textColor = element.innerHTML;
if (textColor === 'In Stock'){
element.style.color = "red";
}
</script>
</html>
答案 1 :(得分:0)
<section class="palm-section text-center" id="palm-section">
<div class="palm-img">
<h1>Palm Hotel</h1>
<div class="break-line"></div>
</div>
</section>
var textColor = document.getElementById('greenStock').innerHTML;
//alert(textColor);
if (textColor == 'In Stock'){
document.getElementById('greenStock').style.color = "#048f00";
} else {
document.getElementById('greenStock').style.color = "any other color"