且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery使用`data` HTML属性创建一个新元素

更新时间:2023-11-29 23:51:34

在创建元素并传递带有属性和方法的对象时,任何jQuery方法都是有效的,因此您可以这样做

When creating an element and passing an object with attributes and methods, any jQuery method is valid, so you can do

$('<div />', { 
    id      : "foo",  
    'class' : "bar",
    text    : "test",          // jQuery text() is called,
    html    : '<span></span>', // jQuery html() is called,
    css     : {                // jQuery css() is called,
        color: 'red'
    },
    on : {                     // calls jQuery's .on('click' ...
        click: function() {
             alert
        }
    }
});

以同样的方式,data=""不是常见的属性,它仅对某些元素有效,例如<object>,而jQuery似乎没有考虑到这一点,因此您无法设置属性,因为jQuery将首先捕获data()方法.

In the same way, data="" is not a common attribute, it's only valid on a few elements, like <object>, and jQuery doesn't seem to account for this, so you can't set a data="" attribute as jQuery will catch the data() method first.

换句话说,这不起作用,而是使用data()设置内部数据对象

In other words, this doesn't work, instead it sets the internal data object using data()

$('<object />', {data : 'somedata'});

一个相当奇怪的解决方法是,这似乎区分大小写,因此jQuery仅在键全部为小写字母的情况下才查找方法,另一方面,jQuery attr()总是将小写的属性,因此请执行以下任一操作这些

A rather strange workaround is that this seems to be case sensitive, so jQuery will only look for the methods if the key is all lowercase, and on the other hand, jQuery attr() will always lowercase attributes, so doing any of these

$('<object>', { id:"foo", 'Data' : "some+data+string" });
$('<object>', { id:"foo", 'daTa' : "some+data+string" });

将实际起作用,并且设置该属性后,该属性将变为小写字母,因此您最终会得到

will actually work, and the attribute will be lower cased when set, so you end up with

<object id="foo" data="some+data+string"></object>

FIDDLE