使用JavaScript变量设置选中单选按钮
有没有办法使用JavaScript变量设置选中的单选按钮?我希望我能通过ID获得单选按钮并更新检查过的收音机使用JavaScript变量设置选中单选按钮,javascript,html,Javascript,Html,有没有办法使用JavaScript变量设置选中的单选按钮?我希望我能通过ID获得单选按钮并更新检查过的收音机 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
var shirtColor = "green";
document.getElementById(shirtColor);
</script>
</head>
<body>
<p>Shirt Color:
<input type="radio" name="shirtColor" id="red" value="red" />
Red
<input type="radio" name="shirtColor" id="green" value="green" />
Green
<input type="radio" name="shirtColor" id="blue" value="blue" />
Blue</p>
</body>
</html>
无标题文件
var shirtColor=“绿色”;
document.getElementById(shirtColor);
衬衫颜色:
红色
绿色
蓝色的
只需将其checked
属性设置为true
:
document.getElementById(shirtColor).checked = true;
这是小提琴:看起来是这样的
btn = document.getElementById("itsID");
btn.checked = true;
您可以这样使用jquery
$("control_id").attr("checked",true);
确保在执行此jquery之前加载元素。。为了安全起见,您应该始终将脚本放在页面末尾的
标记之前,这可能是因为您必须将shirtColor而不是itsID放在页面末尾,“itsID”用作example@user1822824-您必须等待元素可用。将脚本
放在正文
标记的底部,在这些元素已经在页面上之后。