2016-04-09 71 views
-1

我有一些問題,在這裏讓我的HTML表格改變單一td`單擊td時更改bgcolor?

$(document).ready(function(){ 
 
    $("#table1 > td").click(function(){ 
 
     $(this).toggleClass("active"); 
 
    }); 
 
});
table td.active { 
 
    background: #006633; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<table width="100%" border="0" id="table1"> 
 
        <tr> 
 
        <td colspan="6" height="20px" bgcolor="#CCCCCC"><strong>CULTURE</strong></td> 
 
        </tr> 
 
       
 
        <tr> 
 
        <td width="5%"><p align="center">1</p></td> 
 
        <td width="40%">Is the CDP obvious - You Said/We Did Boards; Feedback Stations; Posters?</td> 
 
        <td width="5%" height="20px"><p align="center">1</p></font></td> 
 
        <td width="5%" height="20px"><p align="center">2</p></font></td> 
 
        <td width="5%" height="20px"><p align="center">3</p></font></td> 
 
        <td width="5%" height="20px"><p align="center">4</p></font></td> 
 
        </tr> 
 
    </table>

when the td`被點擊。由於某些原因,當它被點擊時,它什麼也不做。任何人有任何想法,爲什麼這是?

+2

'td'不是'table'的直接孩子。使用'#table1 td'選擇器 –

+0

控制檯中沒有任何東西? –

+1

這個問題是由一個不能再現的問題引起的,或者是一個簡單的印刷錯誤**。 –

回答

2

$("#table1 > td")$("#table1 td"),但這會增加您選擇的匹配。所以,我建議添加一個獨特的屬性(我鼓勵data-*)。

$(document).ready(function(){ 
 
    /* 
 
    $("#table1 td").click(function(){ 
 
     $(this).toggleClass("active"); 
 
    }); 
 
    */ 
 
    // Better 
 
    $("#table1 td[data-toggle]").click(function(){ 
 
     $(this).toggleClass("active"); 
 
    }); 
 
});
table td.active { 
 
    background: #006633; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<table width="100%" border="0" id="table1"> 
 
        <tr> 
 
        <td colspan="6" height="20px" bgcolor="#CCCCCC"><strong>CULTURE</strong></td> 
 
        </tr> 
 
       
 
        <tr> 
 
        <td width="5%"><p align="center">1</p></td> 
 
        <td data-toggle width="40%">Is the CDP obvious - You Said/We Did Boards; Feedback Stations; Posters?</td> 
 
        <td data-toggle width="5%" height="20px"><p align="center">1</p></font></td> 
 
        <td data-toggle width="5%" height="20px"><p align="center">2</p></font></td> 
 
        <td data-toggle width="5%" height="20px"><p align="center">3</p></font></td> 
 
        <td data-toggle width="5%" height="20px"><p align="center">4</p></font></td> 
 
        </tr> 
 
    </table>

+0

好吧,這次我跑了它,並在瀏覽器控制檯中出現錯誤:Uncaught ReferenceError:$未定義 –

+0

jQuery未加載。 –

+0

嗯修正控制檯錯誤只是一個缺失「。無論如何,它仍然沒有運作,只是沒有做任何事情? –

2

$( 「#table1的> TD」)指td爲在表中的第一個子元素。這是不正確的,因爲這是你的情況。只需將其更改爲$(「#table1 td」)即可完成(刪除'>')。

+0

你只是刪除'>' –

0

更改$('#table1 > td')$('#table1 td')作爲td不是table1的第一個孩子。

$(document).ready(function(){ 
     $("#table1 td").click(function(){ 
      $(this).toggleClass("active"); 
     }); 
    }); 

這裏檢查的jsfiddle演示:https://jsfiddle.net/jagrati16/7ychbmht/