关闭 HTML <输入>标签问题

2022-01-18 00:00:00 tags html

为什么 HTML <input> 标签没有像其他 HTML 标签一样获得结束标签,如果我们关闭输入标签会出现什么问题?

我尝试谷歌并找到了编写像这样的输入标签的标准 <input type="text"name="name"> 没有用 </input> 关闭它.

当我使用

Radio 按钮创建输入标签时,我个人感觉到了这个问题

var DOM_tag = document.createElement("input");

这虽然创建了一个单选按钮,但是我将 TextNode 附加到单选按钮

document.createTextNode("Radio Label");

不起作用.它只是显示没有 Radio Label 的单选按钮,如本例所示.

虽然我可以看到完整的代码:

什么是解释?

附言

我遇到的主要问题是输入标签的自动关闭,正如我在问题中提到的,因为我使用的是自动创建的 var DOM_tag = document.createElement("input");结束标记.我该怎么办?

解决方案

这些都是 void 元素.这意味着它们不是为包含文本或其他元素而设计的,因此不需要——事实上,不能有——HTML 中的结束标记.1

但是,它们可以有一个与之关联的 <label>:

单选按钮本质上不能包含文本,因此它们接受文本或其他元素作为内容是没有意义的.接受文本作为输入的控件的另一个问题:它的文本内容应该是它的值还是它的标签?为了避免歧义,我们有一个 <label> 元素,它完全按照它在锡上所说的那样做,我们有一个 value 属性来表示输入控件的值.p><小时>

1 XHTML 不同;根据 XML 规则,每个标签都必须打开和关闭;这是使用快捷语法而不是 </input> 标记完成的,尽管后者同样可以接受:

Why don't the HTML <input> tags get a closing tag like other HTML tags and what would go wrong if we do close the input tag?

I tried to Google and I found the standard to write a input tag like this <input type="text" name="name"> not closing it with a </input>.

I personally felt the problem when I created an input tag for Radio buttons using

var DOM_tag = document.createElement("input");

This though created a radio button, but the TextNode I appended to the radio button with

document.createTextNode("Radio Label");

does not work. It simply shows the radio button with no Radio Label as in this case.

Though I can see the complete code:

<input id="my_id" type="radio" name="radio_name">Radio Label</input>

What is explanation?

P.S.

The main problem that occurred to me is the automatically closing of input tag as I mentioned in the question as I am using var DOM_tag = document.createElement("input"); which automatically creates a closing tag. What should I do about that?

解决方案

These are void elements. This means they aren't designed to contain text or other elements, and as such do not need — and in fact, cannot have — a closing tag in HTML.1

However, they can have a <label> associated with them:

<input id="my_id" type="radio" name="radio_name">
<label for="my_id">Radio Label</label>

Radio buttons by nature can't contain text anyway, so it wouldn't make sense for them to accept text or other elements as content. Another issue with a control that does accept text as input: should its textual content then be its value, or its label? To avoid ambiguity we have a <label> element that does exactly what it says on the tin, and we have a value attribute for denoting an input control's value.


1 XHTML is different; by XML rules, every tag must be opened and closed; this is done with the shortcut syntax instead of a </input> tag, although the latter is equally acceptable:

<input id="my_id" type="radio" name="radio_name" />
<label for="my_id">Radio Label</label>

相关文章