2017-02-13 88 views
-1

我有幾個相同的html塊與svg。 我想通過點擊添加切換類。此代碼不起作用。 Console.log被調用,但不添加類。jquery addClass不能與svg配合使用

$(document).ready(function() { 
     init_svg(); 
     $('.seat').click(function(){ 
      if($(this).hasClass('preorder')){ 
       $(this).removeClass('preorder'); 
       console.log(1); 
      } 
      else{ 
       console.log(2); 
       $(this).addClass("preorder"); 
      }   
     }); 
    }); 
<div class="order" style="top: 260px; right: 370px;"> 
     <svg version="1.1" id="table-4" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" 
     style="transform: rotate(-15deg);" 
     width="100px" height="100px"> 
      <circle class="table" cx="60" cy="60" r="30"></circle> 
      <circle class="seat" cx="28.888" cy="28.884" r="6"></circle> 
      <circle class="seat" cx="17.5" cy="48.608" r="6"></circle> 
      <circle class="seat" cx="17.5" cy="71.384" r="6"></circle> 
      <circle class="seat" cx="28.888" cy="91.108" r="6"></circle> 
      <circle class="seat" cx="48.612" cy="102.497" r="6"></circle> 
      <circle class="seat" cx="71.388" cy="102.497" r="6"></circle> 
      <circle class="seat" cx="91.113" cy="91.109" r="6"></circle> 
      <circle class="seat" cx="102.502" cy="71.385" r="6"></circle> 
      <circle class="seat" cx="102.502" cy="48.609" r="6"></circle> 
      <circle class="seat" cx="91.114" cy="28.883" r="6"></circle> 
     </svg> 
     </div> 

有什麼不對?

+0

我已經刪除了*代碼顯然不打算實際運行(該代碼片段功能不是通用代碼共享工具),因此您的問題中的代碼段*功能可能無法正常運行。 –

+0

你必須使用**舊版本的jQuery:/ https://github.com/jquery/jquery/issues/2199 – vsync

回答

0

JQuery無法將類添加到SVG。

.attr()與SVG工作,你必須做這樣的事情

// Instead of .addClass("newclass") 
$("#item").attr("class", "oldclass newclass"); 
// Instead of .removeClass("newclass") 
$("#item").attr("class", "oldclass"); 

很好的解釋可以在此線程的SO:

jQuery SVG, why can't I addClass?

+0

thx,我不知道這個功能 – Dev

+0

這是不正確的。 https://github.com/jquery/jquery/issues/2199 jQuery **是**能夠將類添加到SVG .... – vsync

相關問題