簡體   English   中英

使用jQuery $(object)動態隱藏表的列

[英]Hide column of table dynamically using jquery $(object)

我有一個簡單的表,其中有兩列,並帶有自定義屬性“ data-cid”。 我想基於數據引用屬性隱藏列。

 $(document).ready(function() { $("th[data-cid='Col_17']").each(function(index, obj) { if ($(obj).prop("className") == "") $(obj).attr("class", "hide-elem"); else $(obj).addClass("hide-elem"); }); } $("td[data-colId='Col_17']").each(function(index, obj) { if ($(obj).prop("class") == "") $(obj).attr("class", "hide-elem"); else $(obj).addClass("hide-elem"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr> <th data-cid="Col_18">sadf</th> <th data-cid="Col_17">asdf</th> </tr> </thead> <tbody> <tr> <td data-cid="Col_18">sadf</td> <td data-cid="Col_17">sadf</td> </tr> </tbody> </table> 

在上述瀏覽器中,無法將類添加到我的th和td中。 有人可以幫我怎么了嗎?

問題:-

您的代碼中有一個額外的}

嘗試這個:-

 $(document).ready(function() { $("th[data-cid='Col_17'], td[data-cid='Col_17']").each(function(index, obj) { if($(obj).prop("className") == ""){ $(obj).attr("class", "hide-elem"); }else{ $(obj).addClass("hide-elem"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr><th data-cid="Col_18">sadf</th> <th data-cid="Col_17">asdf</th></tr> </thead> <tbody> <tr><td data-cid="Col_18">sadf</td> <td data-cid="Col_17">sadf</td></tr> </tbody> </table> 

兩個循環之間有一個額外的} 但是您可以通過將兩個選擇器放在一起將它們簡單地組合成一個循環。 您在td選擇器中還有一個錯字,您使用了data-colId而不是data-cid

 $(document).ready(function() { $("th[data-cid='Col_17'], td[data-cid='Col_17']").each(function(index, obj) { if ($(obj).prop("className") == "") $(obj).attr("class", "hide-elem"); else $(obj).addClass("hide-elem"); }); }); 
 .hide-elem { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr> <th data-cid="Col_18">sadf</th> <th data-cid="Col_17">asdf</th> </tr> </thead> <tbody> <tr> <td data-cid="Col_18">sadf</td> <td data-cid="Col_17">sadf</td> </tr> </tbody> </table> 

您多了一個}而jquery選擇器是錯誤的。 應該是$("th[data-cid='Col_17']")而不是$("th[data-cid='Col_17']")

 $(document).ready(function() { $("th[data-cid='Col_17']").each(function(index, obj) { if ($(obj).prop("className") == "") $(obj).attr("class", "hide-elem"); else $(obj).addClass("hide-elem"); }); $("td[data-cid=Col_17]").each(function(index, obj) { if ($(obj).prop("class") == "") $(obj).attr("class", "hide-elem"); else $(obj).addClass("hide-elem"); }); }); 
 .hide-elem{ display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border=1> <thead> <tr> <th data-cid="Col_18">sadf</th> <th data-cid="Col_17">asdf</th> </tr> </thead> <tbody> <tr> <td data-cid="Col_18">sadf</td> <td data-cid="Col_17">sadf</td> </tr> </tbody> </table> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM