小编典典

如何在JavaScript中设置HTML5必需属性?

javascript

我正在尝试标记Javascript text中所需的输入框。

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

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

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

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

但是现在我想通过Javascript 将required属性设置为“运行时”:

<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"] = "";  

除非我现在提交,否则没有验证检查,也没有阻止。

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

您问该属性的值是什么?
HTML5验证required属性记录为Boolean

4.10.7.3.4 required属性
该required属性是一个布尔属性。指定后,该元素是必需的。

如何定义boolean属性有很多麻烦之处。HTML5规范说明:

元素上的布尔属性的存在表示真实值,而该属性的缺失表示错误值。

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

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

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

但是,该属性的真正价值是什么?
当您查看我的jsFiddle这个问题时,您会注意到,如果required属性在标记中定义:

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

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

edName.attributes.required = [object Attr]

这可能会导致解决方案。


阅读 379

收藏
2020-05-01

共1个答案

小编典典

简洁版本

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

长版
一旦TJ Crowder指出了反射的属性,我就知道以下语法是错误的:

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对象:

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对象:

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

从概念上讲,正确的想法(用一种类型的语言表示)是:

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

这就是为什么:

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

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

除此之外,还反映了一些属性。这意味着您可以从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集合:

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

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

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属性的对象:

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

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

如何设置要求?

设置required属性的正确方法是什么?您有两种选择,即体现属性或通过正确设置属性:

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

严格来说,任何其他值都会“设置”属性。但是Boolean属性的定义规定应仅将其设置为空字符串""以表示true。下面的方法都工作到设定的required 布尔属性,

但不要使用它们:

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

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

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属性的诀窍是很容易意外地将其打开:

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”值将其关闭,而使用trues值将其打开。但是为了清楚起见,请坚持对与错。

如何检查的required?

通过以下.hasAttribute("required")方法检查属性的存在:

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

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

if (edName.required)
{
}
2020-05-01