如何检查是否存在html控件?

Har*_*OTA 1 html javascript

如何检查HTML控件是否存在?

这是我的代码:

var id = ...
if(document.getElementById(id)!=null)
{
   //do something
}
Run Code Online (Sandbox Code Playgroud)

如果html控件是无线电不起作用.

这是怎么做到的?

Dan*_*llo 7

除了上面的评论之外,您还应该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>
Run Code Online (Sandbox Code Playgroud)

它将'It Exists'按预期发出警报.