Set attribute without value

筅森魡賤 提交于 2019-12-17 02:47:05

问题


How do I set a data attribute without adding a value in jQuery? I want this:

<body data-body>

I tried:

$('body').attr('data-body'); // this is a getter, not working
$('body').attr('data-body', null); // not adding anything

Everything else seems to add the second arguments as a string. Is it possible to just set an attribute without value?


回答1:


The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )




回答2:


Perhaps try:

var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");



回答3:


The accepted answer doesn't create a name-only attribute anymore (as of September 2017).

You should use JQuery prop() method to create name-only attributes.

$(body).prop('data-body', true)



回答4:


You can do it without jQuery!

Example:

document.querySelector('button').setAttribute('disabled', '');
<button>My disabled button!</button>

To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.

From MDN Element.setAttribute()



来源:https://stackoverflow.com/questions/13159180/set-attribute-without-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!