为什么要将ID添加到他们的HTML标签中? [英] Why should one add ID to their HTML tags?

查看:100
本文介绍了为什么要将ID添加到他们的HTML标签中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:为什么我们应该将 id 添加到我们的HTML标记中,如果它们在没有它们的情况下运行得很好?我知道他们的一个用途是通过hashtags()在页面中导航,但是有没有其他用途?

解决方案

它们通常用于唯一标识样式(CSS)和脚本(JavaScript等)用途的元素。



但是,如果您只询问HTML和HTML,那么声明性ID有用的一个示例是将< label> 与其< input> <按钮> < textarea>
$ b

 < label for =>通过控制 ex>示例字段:< / label> 
< input type =textname =exid =ex>

如果不指定此属性,则激活标签不起任何作用,但当您使用 for id ,激活标签会使其控件获得焦点。



将表单标签与其控件相关联的另一种方式是将其包含在标签中:

 < label> 
示例字段:
< input type =textname =ex>
< / label>

但是这并不总是适合表单或页面的结构,所以ID引用是作为替代方案提供。

id 属性用于函数的其他情况在Alohci的答案


A simple question: why should we add the id into our HTML tags if they work perfectly well without them? I know that one of their uses is being able to navigate though the page via hashtags (#), but is there any other use for them?

解决方案

They're most often used to uniquely identify elements for styling (CSS) and scripting (JavaScript et al) purposes.

But if you're asking about HTML and only HTML, then one example where declarative IDs are useful is associating a <label> with its <input>, <button> or <textarea> control via its for attribute:

<label for="ex">Example field:</label>
<input type="text" name="ex" id="ex">

Without assigning this attribute, activating the label does nothing, but when you pair both elements together using for and id, activating the label causes its control to gain focus.

The other way to associate a form label with its control is to contain it within the label:

<label>
Example field:
<input type="text" name="ex">
</label>

But this doesn't always suit the structure of a form or a page, so an ID reference is offered as an alternative.

Other circumstances where an id attribute serves a function are covered extensively in Alohci's answer.

这篇关于为什么要将ID添加到他们的HTML标签中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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