JavaScript:设置/移除布尔属性的清晰方法

huangapple go评论95阅读模式
英文:

JavaScript: Clean way to set/remove a bool attribute

问题

用JavaScript时,我经常需要做这样的事情:

  1. if (predicate) el.setAttribute('data-foo', '')
  2. else el.removeAttribute('data-foo')

我真正想做的是这样(干净而干燥):

  1. el.setBoolAttribute('data-foo', predicate) // 期望的函数

这是我想在DOM和Web组件的影子根中多处使用的函数,因此我不太想从模块导入它。JavaScript 是否有任何本地方法?

英文:

With Javascript I often have to do something like this:

  1. if (predicate) el.setAttribute('data-foo', '')
  2. else el.removeAttribute('data-foo')

what I would really like to do is this (nice and DRY):

  1. el.setBoolAttribute('data-foo', predicate) // Desired function

Its a function I would like to use in the DOM, and web component shadow roots, in many places, so its not really a function I would like to import from a module. Does Javascript have any sort of native way?

答案1

得分: 3

你可以使用 Element#toggleAttribute

  1. el.toggleAttribute('data-foo', predicate);
  2. // 如果 predicate 为 true,则添加属性
  3. // 如果为 false,则移除属性
英文:

You can use Element#toggleAttribute:

  1. el.toggleAttribute('data-foo', predicate);
  2. // if predicate is true, the attribute is added
  3. // if it is false, the attribute is removed

答案2

得分: -1

你可以使用WeakMap将任何DOM元素映射到一个JavaScript对象。然后,你可以自由地使用JavaScript数据类型的所有功能:

  1. // 一个全局变量
  2. const domMap = new WeakMap;
  3. // 初始化与元素相关的数据
  4. domMap.set(document.body, { foo: true, bar: new Date() });
  5. // 获取和设置...
  6. console.log(domMap.get(document.body).foo); // true
  7. console.log(domMap.get(document.body).bar); // (当前日期)
  8. domMap.get(document.body).foo = false;
  9. domMap.get(document.body).bar.setFullYear(2000);
  10. consolelog(domMap.get(document.body).foo); // false
  11. console.log(domMap.get(document.body).bar); // 2000年的今天
英文:

Alternatively you can use a WeakMap to map any DOM element to a JavaScript object. Then you are free to use all the power of JavaScript data types:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. // One global variable
  2. const domMap = new WeakMap;
  3. // Initialise element-related data
  4. domMap.set(document.body, { foo: true, bar: new Date() });
  5. // Get and set...
  6. console.log(domMap.get(document.body).foo); // true
  7. console.log(domMap.get(document.body).bar); // (current date)
  8. domMap.get(document.body).foo = false;
  9. domMap.get(document.body).bar.setFullYear(2000);
  10. console.log(domMap.get(document.body).foo); // false
  11. console.log(domMap.get(document.body).bar); // Today in year 2000

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月24日 14:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定