JS原生方法getAttribute(required)获取值实例页面
回到相关文章 »代码:
CSS代码:
.demo pre{display:inline; margin:0;} .co{color:#f30;} .demo p{margin-top:2px;}
HTML代码:
<div class="demo"> <pre><input id="input1" required /></pre> → <input id="input1" required /> <p><code>$("input1").getAttribute("required")</code> → <span id="result1" class="co"></span></p> <pre><input id="input2" /></pre> → <input id="input2" /> <p><code>$("input2").getAttribute("required")</code> → <span id="result2" class="co"></span></p> </div>
JS代码:
var $ = function(id) { return document.getElementById(id); }; for (var i=1; i<=2; i++) { var required = $("input" + i).getAttribute("required"); if (required === "") { required = "空字符串"; } $("result" + i).innerHTML = required + ""; }
效果:
<input id="input1" required />→
$("input1").getAttribute("required")
→
<input id="input2" />→
$("input2").getAttribute.attr("required")
→