javascript 如何检查html控件是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3468758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a html control exists?
提问by Harold Sota
How do I check if an HTML control exists?
如何检查 HTML 控件是否存在?
This is my code:
这是我的代码:
var id = ...
if(document.getElementById(id)!=null)
{
//do something
}
if the html control is radio doesn't work.
如果 html 控件是无线电不起作用。
How is this done?
这是怎么做的?
回答by Daniel Vassallo
Further to your comments above, you should use a unique idfor each radio button, but you can use the same namefor your radio group. Consider the following example:
除了上面的评论之外,您应该id为每个单选按钮使用唯一的按钮,但您可以name为您的单选按钮组使用相同的按钮。考虑以下示例:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Testing document.getElementById()</title>
</head>
<body>
<input type="radio" id="my_radio_1_id" name="my_radios"> My Radio Button 1
<input type="radio" id="my_radio_2_id" name="my_radios"> My Radio Button 2
<script type="text/javascript">
if (document.getElementById('my_radio_1_id')) {
alert('It Exists');
}
</script>
</body>
</html>
It will alert 'It Exists'as expected.
它会'It Exists'按预期发出警报。
回答by Frode
function validate(ValFrm) {
var len = ValFrm.elements.length;
for (i = 0; i < len; i++) {
if (ValFrm.elements[i].required == "Yes") {
if (ValFrm.elements[i].value == "") {
alert('The '+ValFrm.elements[i].title+' is required to contain data.');
ValFrm.elements[i].focus();
return false;
}
}
if (ValFrm.elements[i].type == "radio") {
if (!ValFrm.app[0].checked && !ValFrm.app[1].checked) {
alert('Please accept or deny.');
return false;
}
}
}
}

