简体   繁体   English

在HTML中更改ID属性的方法

[英]Ways to change id attribute in html

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" . 当我单击其中一些列表项时,我希望我的<body>的id从id="index"更改为id="collection"

What's the most efficient way to do that? 最有效的方法是什么?

  1. Should I use JavaScript? 我应该使用JavaScript吗?
  2. Should I put all the body code in a {% block %} and override it when I click on the special list items? 单击特殊列表项时,是否应该将所有正文代码放在{% block %}并覆盖它?
  3. An other way? 其它的办法?

From a purely JavaScript persepctive, the simplest and best way of changing the body's ID is 从纯粹的JavaScript角度来看,更改主体ID的最简单最好的方法是

document.body.id = "collection";

However, you may be better off using a class to avoid any potential conflict of your ID with any other ID in the page. 但是,最好使用一个类,以避免ID与页面中的任何其他ID发生任何潜在冲突。 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. 鉴于页面中只有一个<body>元素,并且可以通过JavaScript中的document.body和CSS中的body进行引用,为body提供ID似乎并不是非常有用。

If you want to change an element in the page without reloading the whole page then JavaScript is your only option. 如果要更改页面中的元素而不重新加载整个页面,则JavaScript是您唯一的选择。 If the change is vital to the functionality of your page, you should also provide a non-JavaScript fallback. 如果更改对页面功能至关重要,则还应该提供非JavaScript后备功能。

Should I use JavaScript? 我应该使用JavaScript吗?

Yes, based on the knowledge that you want this to happen during a click event. 是的,基于您希望在单击事件期间发生这种情况的知识。 The most efficient way would be 最有效的方法是

document.body.id = "collection";

a less efficient way would be 效率较低的方法是

document.getElementById("index").id = "collection";

Depends what you mean by “efficient”. 取决于您所说的“有效”。 Using JavaScript means the id gets changed without another HTTP request being made to your server, so the user doesn't have to wait for the page to reload. 使用JavaScript意味着无需更改另一个服务器的HTTP请求即可更改id ,因此用户不必等待页面重新加载。

However, if they revisit or reload the page after clicking on one of these list items, the list will go back to the way it was when the page was loaded. 但是,如果他们在单击这些列表项之一后重新访问或重新加载页面,则列表将返回到加载页面时的状态。 That might not be optimal for your context. 对于您的上下文,这可能不是最佳选择。

I would do it using jQuery, with the line $('#index').attr('id', 'collection'); 我将使用jQuery,并在行$('#index').attr('id', 'collection'); .

document.getElementById( "index" ).id = "collection";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM