![](/img/trans.png)
[英]How to: Conditionally format a <td>, that is generated via MySQL query, based on content and using PHP/JavaScript
[英]conditionally format php output with javascript
我想在<div>
元素上有條件地(基於日期和時間)將Javascript不同的CSS樣式應用於包含來自Mysql數據庫的Php數據輸出的<div>
元素。 php會生成一個事件列表,這些事件分為多個<div>
,其中<div>
會根據其相對於實際日期的日期/時間獲得不同的顏色。 (因此,如果事件日期/時間是將來的日期,則顏色將是藍色,如果過去是灰色,則該顏色將是灰色。)我知道PHP解決方案將使用服務器的日期/時間,而javascript將使用瀏覽器的日期/時間,所以我選擇了javascript作為基於日期/時間的條件格式。 我也了解javascript需要等到整個頁面加載完畢,包括php查詢的結果。 (我也了解我對javascript和php知之甚少。)
以下是我擁有的html和php代碼。 此php查詢前10個事件,並將它們顯示在引導表中按日期排序的列表中。 div #timecode
是我要條件格式化的格式(此示例php代碼不包含分頁php代碼,並從數據庫中返回前10條記錄):
<div class="row"> <div class="venuelista"> <div class="col-sm-9 col-md-9 col-lg-9"> <table class="table">
<tbody> <?php while ($row = mysql_fetch_assoc($rs_result)) { ?> <tr> <td class="col-md-7"> <div id="timecode" padding="right:5px"><?php echo $row['esemeny_disp_mm_dd']; ?></div> <div class="eventListTitle"><?php echo $row['esemeny_cim']; ?><br><?php echo $row['esemeny_jelleg']; ?></div> </td> <td class="col-md-5"> <div class="eventListTitle"><?php echo $row['esemeny_helyszin']; ?> </div> </td> </tr> <?php }; ?> </tbody> </table> </div> </div>
在Mysql數據庫中,我具有“事件日期”字段和單獨的“事件時間”字段。
這是我在網上(可能是在本網站上)找到的javascript,用於根據日期/時間格式化div #timecode
(這只是測試它是否可針對修復日期-確實如此):
<script> $(document).ready(function() { var curtime = new Date(), curday = curtime.getDate(), curmonth = curtime.getMonth()+1; if(curmonth == 7 && curday == 20) $('#timecode').addClass('circle-disappear-blue'); else $('#timecode').addClass('circle-disappear-grey'); }); </script>
問題:javascript僅格式化列表的第一個php結果。 我以為$(document).ready(function()
將允許它格式化所有10個列表項。再次抱歉,我對問題的格式不正確-我對代碼示例函數沒有共同的理解。
對此有任何見識,不勝感激。
編輯:JavaScript現在看起來像這樣
<script>
$(document).ready(function() {
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
var curtime = new Date(),
curday = curtime.getDate(),
curmonth = curtime.getMonth()+1;
if(curmonth == 7 && curday == 19)
$('#blue-condtional').addClass('circle-disappear-blue');
else
$('#blue-condtional').addClass('circle-disappear-grey');
});
</script>
例如,將id添加到表中
<table class="table" id="mytableid">
然后使用適當的選擇器
$('#mytableid tr td:first-child').addClass('circle-disappear-blue');
另一個選擇是將類添加到要更改顏色的類型,例如“ blue-condtional”
if(curmonth == 7 && curday == 20) {
$('.blue-condtional').addClass('circle-disappear-blue');
} else {
$('.blue-condtional').addClass('circle-disappear-grey');
}
並改變
<div id="timecode" padding="right:5px">
至
<div class="blue-condtional">
順便說一句,使用內聯樣式不是一個好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.