在HTML中更改ID属性的方法 [英] Ways to change id attribute in html

查看:163
本文介绍了在HTML中更改ID属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个网站,但我有一个未排序的列表,其中包含一些列表元素。当我单击其中某些列表项时,我希望我的< body> 的I​​D从 id = index id = collection

I'm building a website and I have an unsorted list with some list elements. When I click on some of these list items I want my <body>’s id to change from id="index" to id="collection".

最有效的方法是什么?


  1. 我应该使用JavaScript吗?

  2. 是否应该将所有正文代码放在中{%block%} 并在我单击特殊列表项时将其覆盖?

  3. 另一种方式?

  1. Should I use JavaScript?
  2. Should I put all the body code in a {% block %} and override it when I click on the special list items?
  3. An other way?


推荐答案

从纯JavaScript角度讲,更改主体ID的最简单,最好的方法是

From a purely JavaScript persepctive, the simplest and best way of changing the body's ID is

document.body.id = "collection";

但是,最好使用一个类,以避免ID与其他任何潜在冲突页面中的ID。鉴于页面中只有一个< body> 元素,并且可以通过进行引用,因此给主体提供ID似乎并不是非常有用。 JavaScript中的document.body 和CSS中的 body

However, you may be better off using a class to avoid any potential conflict of your ID with any other ID in the page. Giving the body an ID doesn't seem terribly useful given that there is only one <body> element in the page and it can be referenced via document.body in JavaScript and body in CSS.

如果要更改页面中的一个元素而不重新加载整个页面,那么JavaScript是您唯一的选择。如果更改对页面的功能至关重要,则还应该提供非JavaScript后备功能。

If you want to change an element in the page without reloading the whole page then JavaScript is your only option. If the change is vital to the functionality of your page, you should also provide a non-JavaScript fallback.

这篇关于在HTML中更改ID属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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