gpt4 book ai didi

javascript - 在 jQuery 中选择多个元素的语义 "correct"方式?

转载 作者:太空狗 更新时间:2023-10-29 15:26:41 26 4
gpt4 key购买 nike

我经常使用作为识别一组相关元素的手段,例如:

<input value="10" class="sum-this" />
<input value="20" class="sum-this" />
<input value="30" class="sum-this" />

sum-this 类没有 CSS,也没有在任何 CSS 文件中定义 - 它只是在一些 jQuery 中使用 - 例如:

var total = 0;
$(".sum-this").each(function(i, el){
total += parseInt($(el).val());
});
console.log(total); // 60?

有没有正确的方法来做到这一点?我应该使用另一个属性吗? rel 还是 data-*

最佳答案

正如@Pointy 和@JustinPowell 在评论中所述,这是完全有效的。事实上,在 W3C HTML4 规范中也明确指出,将 class 属性用于选择样式以外的目的是完全有效的。我引用:

The class attribute, on the other hand, assigns one or more class names to an element; the element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles in HTML:

  • As a style sheet selector (when an author wishes to assign style information to a set of elements).
  • For general purpose processing by user agents.

但是,HTML5 还为此添加了自定义 data-* 属性(其中 * 是自定义字符串)。


链接

  1. A blog post discussing your question
  2. W3C HTML4 attributes
  3. W3C HTML 5 data attribute

关于javascript - 在 jQuery 中选择多个元素的语义 "correct"方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40767175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com