如果元素是唯一的,是否可以使用javascript更改ID? [英] Is it an ok practice to change an ID using javascript if the element is unique?

查看:38
本文介绍了如果元素是唯一的,是否可以使用javascript更改ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无序列表,我在其中使用ID来标识最后单击的当前列表项.单击其他项目时,我正在使用js将ID切换到列表中的其他项目,以便可以应用样式.

I have an unordered list, where I am using an ID to identify the current list item that was last clicked. On click of a different item, I am using js to switch the id to a different item in the list, so that styling could be applied.

在我看来,应该将只能使用一次的唯一项(选定的li项)标识为ID,这就是我的直觉,这就是为什么这样做的原因,但我被告知这样做是错误的做法.

It seems intuitive to me that a unique item that can only be used once (a selected li item) should be identified as an ID, and that is why I did that, but I was told it is bad practice to do so.

推荐答案

我不会这样做.相反,这似乎是您发现 HTML 5的数据属性的机会,您可以将其用于CSS样式(使用属性选择器)和JS使用(通过 dataset 或jQuery的 .data()方法).来自MDN的快速定义:

I wouldn't do so. This rather seems an opportunity for you to discover HTML 5's data attribute, which you can use for both CSS styling (using attribute selector) and JS use (with dataset or jQuery's .data() method). Quick definition from MDN :

HTML5在设计时考虑了可扩展性,与特定元素相关联,但无需定义任何元素意义.data- *属性使我们可以在以下位置存储其他信息标准的,语义HTML元素,没有其他技巧,例如classList,非标准属性,DOM上的其他属性,或setUserData.

HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as classList, non-standard attributes, extra properties on DOM, or setUserData.

在HTML端:

<!-- You can use data without value, and just test its presence -->
<li data-selected> 
    ...
</li>

在CSS中:

li[data-selected]{
   ...
}

这篇关于如果元素是唯一的,是否可以使用javascript更改ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆