Javascript 用数据属性创建div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14301540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:19:46  来源:igfitidea点击:

Create div with data attributes

javascriptjquery

提问by ilyo

I am creating div the following way

我正在通过以下方式创建 div

$('<div/>', {
    "class" : 'draggable player' + player + ' unit unit' + unit
})

And I can't find what other properties I can assign to it the same way I assign class. especially if I can assign dataor attr?

而且我找不到可以像分配类一样的方式分配给它的其他属性。特别是如果我可以分配dataattr

回答by Brandon Kelly

According to the jQuery()function documentation (alias of $()), you can define attributes, events, and methods within that second parameter.

根据jQuery()函数文档(别名为$()),您可以在第二个参数中定义属性、事件和方法。

So yes, anything you'd define using attr()is fair game. That includes “data-whatever” attributes(which are oddly accessible via $elem.data('whatever')), however they will not be saved to jQuery.datalike any variables defined via $elem.data('name', 'value')(at least until you call $elem.data('whatever')–?see http://api.jquery.com/jQuery.data/#entry-longdesc-1).

所以是的,你定义使用的任何东西attr()都是公平的游戏。这包括“data-whatever”属性(可以通过 奇怪地访问$elem.data('whatever')),但是它们不会被保存为jQuery.data通过定义的任何变量$elem.data('name', 'value')(至少在您调用之前$elem.data('whatever')-?请参阅http://api.jquery.com/jQuery.data /#entry-longdesc-1)。

So to clarify:

所以要澄清:

var $elem = jQuery('<div/>', { 'data-test': "Testing" });

will create this element, and return a jQuery object containing it:

将创建这个元素,并返回一个包含它的 jQuery 对象:

<div data-test="Testing"></div>

From there, you will be able to do:

从那里,您将能够:

jQuery.data($elem[0], 'test'); // => undefined
$elem.data('test');            // => "Testing"
jQuery.data($elem[0], 'test'); // => "Testing"

Of course, $elem.attr('data-test')will also work.

当然,$elem.attr('data-test')也会起作用。

回答by Joseph Silber

You can assign any attributes you want:

您可以分配所需的任何属性:

$('<div/>', {
    "class" : 'draggable player' + player + ' unit unit' + unit,
    "data-info": 'Anything you want',
    "even-non-validating-attributes": 'ANYTHING!!'
});

Here's the fiddle: http://jsfiddle.net/vCaym/

这是小提琴:http: //jsfiddle.net/vCaym/