2017-03-22 26 views
0

我想添加'紅'的顏色,而價值的負面和'綠色'的正面價值的顏色。我試了很多想法,爲什麼它不工作,但沒有取得成功。JavaScript和CSS - 我是這樣做的嗎?

請更正我的腳本。下面的代碼有什麼問題:

<!DOCTYPE html> 
<html> 
<head> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 

<script type="text/javascript"> 
$(document).ready(function() { 
$(".status") 
    .filter(function() { 
    return $(this).html() < 0; 
}) 
    .parent().css('color', 'blue'); 
}); 
</script> 

</head> 
<body> 

<span class="status">10</span><br /> 
<span class="status">-1</span> 

</body> 
</html> 

回答

1

試試這個!

//run code for every element with the status class 
 
$(".status").each(function() { 
 

 
    //cache which element is $(this) to make code load faster 
 
    $this = $(this); 
 

 
    //cache the text of $(this) 
 
    //parseInt() makes "text" into number so that we can use ">", "<", etc.. 
 
    number = parseInt($this.text()); 
 
    
 
    //if number is great than or equal to zero, make it green 
 
    if (number >= 0) { 
 
    $this.css("color", "green") 
 

 
    //if the number is NOT greater than or equal to zero, make it red 
 
    } else { 
 
    $this.css("color", "red") 
 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<div class="status">-10</div> 
 
<div class="status">2</div>

注:這讓0也是綠色。

改進代碼:

  • 使用[.each()][1],這樣就可以對每一個元素
  • 使用$(this)運行代碼來選擇元素

你可以使用.html()文本而不是.text()也許你的filter功能,但這只是我怎麼做:)

$(document).ready(function() { 
 

 
$(".status").each(function(){ //add .each 
 

 
    $(this).filter(function() { //add $(this) 
 
    return $(this).html() < 0; 
 
}) 
 
    .css('color', 'blue'); //remove parent 
 
}); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<div class="status">-10</div> 
 
<div class="status">2</div>

+0

這會認爲0爲負值。 –

+0

解釋爲什麼OP代碼無法正常工作,以及爲什麼您的操作的關鍵點(例如,有多個具有ID狀態的項目,以便您需要遍歷它們)將改進您的答案。 – Dijkgraaf

1

與您的代碼的主要問題是,您比較的字符串(的html()值)爲整數。您還可以通過提供處理邏輯的addClass()函數來簡化代碼。試試這個:

$(".status").addClass(function() { 
 
    return parseInt($(this).html(), 10) < 0 ? 'negative' : 'positive'; 
 
});
.positive { color: #0C0; } 
 
.negative { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="status">10</span><br /> 
 
<span class="status">-1</span>

注意,這在技術上考慮0是一個 '積極的' 價值。如果您不想要這種行爲,則可以輕鬆更改處理函數addClass()中的邏輯。

+0

幹得好!這麼緊! –

相關問題