2014-12-01 69 views
1

的所有類的數組我知道這可能看起來像一個重新發布,但我不能讓代碼工作的社會作出here
請與SVG元素

我所試圖做的就是在我點擊元素中列出的所有類的數組。
我點擊的元素是從SVG對象<g></g>元素。

我想將類(在一個數組中)發佈到模塊和<g>元素的ID。這裏是我的代碼:

//reveal Modal when when clicking on an item box. 
$(document).ready(function() { 
    $('.items').click(function() { 
     $.ajax({ 
      type: "POST", 
      url: "/includes/functions/choose_item.php", 
      data: { id: this.id, class: this.className} 
     }) 
      .done(function() { 
       $('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ; 
      }) 
    }); 
}); 

它張貼到我的PHP腳本,ID的作品,但類是在baseval和animval的數組,我想baseval的所有值的數組只。

這是數組我得到:

Array ([animVal] => items hero_item [baseVal] => items hero_item) 

感謝您的幫助。

回答

2

SVG元素並沒有真正上課像普通的元素,和className屬性返回一個特殊的對象,通常是一個SVGAnimatedString看起來像

{animVal: "class class2", baseVal: "class class2"} 

class屬性實際上只是一些陌生感常規屬性,所以你需要使用getAttribute('class')代替,或在jQuery的attr()獲取屬性的值

$(document).ready(function() { 
    $('.items').click(function() { 
     $.ajax({ 
      type : "POST", 
      url : "/includes/functions/choose_item.php", 
      data : { 
       id  : this.id, 
       'class' : $(this).attr('class') 
      } 
     }).done(function() { 
      $('#choose_item_modal').foundation('reveal', 'open', "/includes/functions/choose_item.php") ; 
     }); 
    }); 
}); 

注意class是javascript中的關鍵字,因此應該引用它。
如果你需要一個數組,你可以做$(this).attr('class').split(/\s+/);

TEST

+0

啊wauw謝謝了很多! 這工作完美,我不知道關於類。偉大的事情,你解釋了。 – uruloke 2014-12-01 19:05:04

+0

與任何常規元素一樣,SVG元素也可以具有類屬性,但是確實如此,它在DOM中以不同的方式公開(不幸的歷史錯誤)。我認爲這裏的解決方案是好的,存在於大多數最新的瀏覽器的替代是較新的API ['Element.classList'(https://developer.mozilla.org/en-US/docs/Web/API/Element。 classList),它在svg和html元素上都是一樣的。 – 2014-12-08 15:01:51