2014-12-01 67 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