创建一个包含 SVG 元素所有类的数组

Make an array with all classes of an SVG element

本文关键字:元素 数组 SVG 包含 一个 创建      更新时间:2023-09-26

我知道这可能看起来像一个转发,但我无法让社区在这里制作的代码工作。

正在尝试做的是制作一个我正在单击的元素中列出的所有类的数组。
我正在单击的元素是来自 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 )

感谢您的任何帮助。

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+/);

测试