網站搜尋

javascript - 設定無值屬性


我如何在 jQuery 中設定資料屬性而不添加值?我想要這樣:

<body data-body>

我試過:

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

其他所有東西似乎都將第二個參數作為字串添加。是否有可能僅設置一個沒有值的屬性?

答案#1

attr() 函數也可以作為設定函數使用。你可以直接傳入一個空字串。

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

空字串將只會建立沒有值的屬性。

<body data-body>

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

attr( 屬性名稱 , 值 )

答案#2

或許可以試試:

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

答案#3

截至2017年9月,被接受的答案不再只創建名稱屬性。

你應該使用 JQuery 的 prop() 方法來創建只有名稱的屬性。

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

答案#4

你可以不用 jQuery 也能做到!

範例:

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

要設定布林屬性的值,例如 disabled,你可以指定任何值。建議使用空字串或屬性名稱。重要的是,如果屬性存在,不論其實際值為何,其值都被視為 true。屬性不存在則表示其值為 false。通過將 disabled 屬性的值設為空字串(""),我們將 disabled 設為 true,這會導致按鈕被禁用。

來自 MDN 的 Element.setAttribute()

答案#5

不確定這是否真的有益,或者為什麼我偏好這種風格,但我(在原生 JS 中)所做的是:

// Add
document.querySelector('#selector')
    .toggleAttribute('data-something', true);

// Remove
document.querySelector('#selector')
    .toggleAttribute('data-something', false);

// Toggle
document.querySelector('#selector')
    .toggleAttribute('data-something');

這可能會將屬性以全小寫形式新增而不帶值,或者如果元素上已經存在該屬性則將其移除。


語法...

toggleAttribute(name, force)

參數...

- force 可選

一個布林值,其具有以下效果:

如果完全沒有指定,toggleAttribute 方法會「切換」名為 name 的屬性——如果它存在則移除,否則如果它不存在則添加。如果為 true,toggleAttribute 方法會添加名為 name 的屬性;如果為 false,toggleAttribute 方法會移除名為 name 的屬性。

來源:toggleAttribute