[英]Jquery - How can i add a custom data attribute when appending an html element
I am currently appending an element like so 我目前正在像这样添加一个元素
$('#action_existing_email').append($('<option>', {
value: templates[i].id,
text: templates[i].name
}));
I want to append a data attribute like data-version="1"
我想附加一个数据属性,例如data-version="1"
Is there any way I can add something like data: ("foo", "bar")
to get data-foo="bar"
有什么办法可以添加类似data: ("foo", "bar")
以获取data-foo="bar"
Looks like you can give data as an object. 看起来您可以将数据作为对象。
$(document.body).append($('<div>', { id: 'test1', data: { name: 'Timmy' } })); console.log($('#test1').data('name'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can simply do it like this 你可以这样简单地做
$('#action_existing_email').append($('<option>', { value: "value", text: "text", id : "opt", data: { version: 1 } })); console.log($("#opt").data('version'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="action_existing_email"></select>
PS Note that data-*
properties are cached by jQuery internally, and they are not added as attributes to the DOM, so they are not visible: PS注意, data-*
属性由jQuery内部缓存,并且不会作为属性添加到DOM,因此它们不可见:
You can instead use template literals to form the HTML however you want, so that you're not limited by a third party API. 您可以改用模板文字来形成所需的HTML,这样就不受第三方API的限制。
$('#action_existing_email').append(`
<option value=${templates[i].id} data-version=1>${templates[i].name}</option>`
);
This lets you see exactly what you're appending, without having to also understand the inner workings of an API. 这使您可以准确地看到要添加的内容,而不必了解API的内部工作原理。
And of course, you're then just a step away of going fully native. 当然,您离完全本地化仅一步之遥。
var templates = [ {id:"foo", name:"FOO"} ]; var email = document.querySelector('#action_existing_email'); for (var i = 0; i < templates.length; i++) { email.insertAdjacentHTML("beforeend", `<option value=${templates[i].id} data-version=1>${templates[i].name}</option>` ); } console.log(email.options[0].dataset.version);
<select id=action_existing_email></select>
And shorten your code by using a for-of
loop instead. 并通过使用for-of
循环来缩短代码。
var templates = [ {id:"foo", name:"FOO"} ]; var email = document.querySelector('#action_existing_email'); for (const o of templates) { email.insertAdjacentHTML("beforeend", `<option value=${o.id} data-version=1>${o.name}</option>`); } console.log(email.options[0].dataset.version);
<select id=action_existing_email></select>
Or you can simply set data-* attribute with a string like the following. 或者,您可以简单地使用如下字符串设置data- *属性。
$('select').append($('<option>', { value: 'foo', text: 'foo', 'data-version': 1 })); console.log($('option').data('version'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select></select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.