2016-08-04 21 views
0

我加入動態使用jQuery像這樣一個div:條件和動態添加的div類與jQuery

$('#content').append('<div class="tiles color m-b-10">some text</div>'); 

我想類值「顏色」由「綠色」來代替,如果x> 0, 「紅色」,否則

我試過以下(在變化,沒有引號,單引號和雙引號等),但似乎沒有任何工作。

$('#content').append('<div class="tiles'+ x > 0 ? "green" : "red"+ ' m-b-10">some text</div>');`enter code here` 

我的問題是a)是否可行? b)如果是,如何?

+0

什麼是HTML?我認爲這與你解釋 – Sherlock

回答

0

我這個這將工作

$('#content').append('<div class="tiles '+ (x > 0 ? "green" : "red")+ ' m-b-10">some text</div>'); 
+0

這工作完美,我試過除括號(甚至嘗試大括號)之前的所有內容 謝謝 –

1

這是你要找的嗎?

$(document).ready(function(){ 
 
    var x = 5; 
 
    var color = x > 0 ? 'green' : 'red'; // Preprocess the class first 
 
    $('#content').append('<div class="tiles ' + color + ' m-b-10"></div>'); 
 
    
 
    x = -1; 
 
    var color = x > 0 ? 'green' : 'red'; // Preprocess the class first 
 
    $('#content').append('<div class="tiles ' + color + ' m-b-10"></div>'); 
 
    
 
    // For one liner solution 
 
    x = 10; 
 
    $('#content').append('<div class="tiles ' + (x > 0 ? 'green' : 'red') + ' m-b-10"></div>'); 
 
});
div { 
 
    width: 50px; 
 
    height:50px; 
 
} 
 
.green{ 
 
    background-color: green; 
 
} 
 

 
.red { 
 
    background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="content"> 
 
</div>

+0

的想法有所不同,但我選擇了一個班輪,就像下面的ubm解決方案。謝謝 –

+0

@Panikos我可以修改它,我只是認爲我的代碼的可讀性 – Sherlock