[英]Add non-standard attribute to a select tag with Javascript
I want to create a select element through JavaScript and I want to set an attribute to it called data-placeholder
. 我想通过JavaScript创建一个select元素,我想设置一个名为
data-placeholder
的属性。
How can we assign non-standard attributes with JavaScript without the browser complaining with: 如何在没有浏览器抱怨的情况下使用JavaScript分配非标准属性:
Uncaught referenceError: Invalid left-hand side in assignment
Code that cause the error: 导致错误的代码:
select1.data-placeholder="Choose ...";
因为它用javascript说不是jquery ...
yourElement.setAttribute('data-placeholder','value');
Here's a pretty simple non-jQuery way to achieve this; 这是一个非常简单的非jQuery方法来实现这一点;
var el = document.createElement('select');
el.setAttribute('data-placeholder', 'placeholder value');
document.body.appendChild(el);
I've created a very simple JSFiddle to demonstrate it. 我已经创建了一个非常简单的JSFiddle来演示它。
Hope that helps! 希望有所帮助!
JQuery使这很简单:
$("<select></select>").attr("data-placeholder", "value").appendTo($element);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.