如何在 Javascript 中设置 HTML5 必需属性? [英] How to set HTML5 required attribute in Javascript?

查看:39
本文介绍了如何在 Javascript 中设置 HTML5 必需属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Javascript 中将 text 输入框标记为 必需.

I am trying to mark a text input box as required in Javascript.

<input id="edName" type="text" id="name">

如果该字段最初被标记为required:

If the field is initially marked as required:

<form>
    <input id="edName" type="text" id="name" required><br>
    <input type="submit" value="Search">
</form>

当用户尝试提交时,他们会收到验证错误:

when the user tries to submit they are given a validation error:

但现在我想通过 Javascript 在 "runtime" 设置 required 属性:

But now I want to set the required attribute at "runtime", through Javascript:

<form>
    <input id="edName" type="text" id="name"><br>
    <input type="submit" value="Search">
</form>

带有相应的脚本:

//recommended W3C HTML5 syntax for boolean attributes
document.getElementById("edName").attributes["required"] = "";         

除了我现在提交的时候,没有验证检查,没有阻止.

Except when I submit now, there is no validation check, no block.

设置HTML5 验证布尔属性正确方法是什么?

jsFiddle

HTML5 验证 required 属性已记录 作为 Boolean:

The HTML5 validation required attribute is documented as a Boolean:

必需 属性是一个 布尔属性.指定时,该元素是必需的.

4.10.7.3.4 The required attribute

The required attribute is a boolean attribute. When specified, the element is required.

关于如何定义 boolean 属性有很多令人担忧的地方.HTML5 规范说明:

There is a lot of hand-wringing about how to define a boolean attribute. The HTML5 spec notes:

元素上布尔属性的存在代表真值,不存在该属性代表假值.

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

如果该属性存在,则其值必须是空字符串,或者是与该属性的规范名称不区分大小写的 ASCII 匹配值,且没有前导或尾随空格.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

这意味着您可以通过两种不同的方式指定 required boolean 属性:

This means that you can specify a required boolean attribute two different ways:

edName.attributes.required = ""; //the empty string
edName.attributes.required = "required"; //the attribute's canonical name

但是属性的值真的是什么?

当你查看我关于这个问题的jsFiddle时,你会注意到如果需要 属性在标记中定义:

But what is the value of the attribute really?

When you look at my jsFiddle of this problem, you'll notice that if the required attribute is defined in the markup:

<input id="edName" type="text" id="name" required>

那么属性的值是不是空字符串,也不是属性的规范名称:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

这可能会导致一个解决方案.

That might lead to a solution.

推荐答案

短版

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

长版

曾经T.J.克劳德设法指出反射属性,我了解到以下语法错误:

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value;    //bad! Overwrites the HtmlAttribute object
value = element.attributes.name;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

必须通过element.getAttributeelement.setAttribute:

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

这是因为该属性实际上包含一个特殊的HtmlAttribute对象:

This is because the attribute actually contains a special HtmlAttribute object:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo;              //returns HtmlAttribute object, not the value of the attribute

通过将属性值设置为true",您错误地将其设置为 String 对象,而不是它所需的 HtmlAttribute 对象:

By setting an attribute value to "true", you are mistakenly setting it to a String object, rather than the HtmlAttribute object it requires:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

概念上正确的想法(用类型化语言表达)是:

Conceptually the correct idea (expressed in a typed language), is:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

这是为什么:

  • getAttribute(name)
  • setAttribute(name, value)

存在.他们负责将值分配给内部的 HtmlAttribute 对象.

exist. They do the work on assigning the value to the HtmlAttribute object inside.

在此之上,一些属性被反映.这意味着您可以通过 Javascript 更好地访问它们:

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
//element.removeAttribute("required");
element.required = false;

不想做的是错误地使用.attributes集合:

What you don't want to do is mistakenly use the .attributes collection:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

测试用例

这导致围绕 required 属性的使用进行测试,比较通过该属性返回的值和反射的属性

Testing Cases

This led to testing around the use of a required attribute, comparing the values returned through the attribute, and the reflected property

document.getElementById("name").required;
document.getElementById("name").getAttribute("required");

结果:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

尝试直接访问 .attributes 集合是错误的.它返回代表 DOM 属性的对象:

Trying to access the .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

这解释了为什么您永远不应该直接与 .attributes 收集交谈.您不是在操纵属性的,而是在操纵代表属性本身的对象.

This explains why you should never talk to the .attributes collect directly. You're not manipulating the values of the attributes, but the objects that represent the attributes themselves.

在属性上设置 required 的正确方法是什么?您有两种选择,要么是反射的属性,要么是通过正确设置属性:

What's the correct way to set required on an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

严格来说,任何其他值都会设置"该属性.但是Boolean 属性的定义规定它只应设置为空字符串"" 以表示true.以下方法都可以设置required Boolean 属性,

Strictly speaking, any other value will "set" the attribute. But the definition of Boolean attributes dictate that it should only be set to the empty string "" to indicate true. The following methods all work to set the required Boolean attribute,

不要使用它们:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

我们已经了解到尝试直接设置属性是错误的:

We already learned that trying to set the attribute directly is wrong:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

如何清除需要?

尝试删除required 属性的技巧是很容易意外打开它:

How to clear required?

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

使用无效方式:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

当使用反射的 .required 属性时,您还可以使用任何 "falsey" 值将其关闭,并使用真值将其打开.但为了清楚起见,请坚持真假.

When using the reflected .required property, you can also use any "falsey" values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

通过.hasAttribute("required")方法检查属性是否存在:

Check for the presence of the attribute through the .hasAttribute("required") method:

if (edName.hasAttribute("required"))
{
}

您也可以通过 Boolean 反映的 .required 属性进行检查:

You can also check it through the Boolean reflected .required property:

if (edName.required)
{
}

这篇关于如何在 Javascript 中设置 HTML5 必需属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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