2013-07-27 44 views
2

追加之間以下切換,並刪除不工作:jQuery的切換,並刪除不工作,我預計

$('.t').click(function() { 
      var className = $(this).data('class'); 
      $(this).toggleClass(className).toggleClass(className+'1'); 

      var newTable='<table style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>'; 
      $("#newDiv").append(newTable).remove(newTable); 
     }); 

HTML

<div class="t a" data-class="a"> 8cghfghfghfghfg</div> 
<div class="t b" data-class="b">20cghfghfghfghfg</div> 
<div class="t c" data-class="c"> 4cghfghfghfghfg</div> 

<div id="newDiv"></div> 

Working Demo Here..

這裏,是什麼我想要做的是..如果我點擊div.t,我想刪除特定的類(例如:.a)並添加相應的類(例如.a1),這個我達到了。

但是我想在第一次點擊的時候添加一個表格,想在第二次點擊時刪除添加的表格。

我怎樣才能做到這一點,請誰能幫我把...

感謝

+0

使用'$(本).removeClass(類名).addClass(類名+ '1')'類之間 –

+0

toggleing工作,但我想之間toggeling附加和刪除也.. .. @ DKM – user123456789

回答

4

要切換追加和刪除,您可以使用點擊元素的data屬性。它是一種更簡潔的方法:

$('.t').click(function() { 
     //general stuff must happen everytime class is clicked 
     //get the className from data- attr 
     var className = $(this).data('class'); 
     //toggling to change color 
     $(this).toggleClass(className).toggleClass(className + '1'); 

     //check if its clicked already using data- attribute 
     if ($(this).data("clicked")) { 
      //remove it if yes 
      $("#newDiv").find("#tablefor-" + className).remove(); 
     } else { 
      //new table - note that I've added an id to it indicate where it came from 
      var newTable = '<table id="tablefor-' + className + '" style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1' + className + '</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>'; 

      //append table     
      $("#newDiv").append(newTable); 
     } 
     //reverse the data of clicked 
     $(this).data("clicked", !$(this).data("clicked")); 
    }); 

演示:http://jsfiddle.net/hungerpain/m9ak9/11/

+0

在這裏我有一個更多的問題,我可以問..... – user123456789

+0

請問它作爲單獨的問題。有很多的人可以幫助這裏:) – krishgopinath

+0

它只涉及到這個問題..... – user123456789

0

只需使用一個if開關來確定羯羊表已經存在。我修改了小提琴證明這一點:http://jsfiddle.net/m9ak9/6/

我添加了一個id表,使其easiert識別,但你也可以尋找它是這樣的:

var findTableInDiv = $('#newDiv').find('table'); 
+0

感謝您的答案,但我想爲每個div的手段(div.ta,div.tb,div.tc)添加一個表,並刪除以及.. @當務之急 – user123456789