我试过在jsfiddle.net中运行它并且它工作正常。 http://jsfiddle.net/AdTK3/
HTML
<input name="rdoNationality" class="rdoNationality" type="radio" checked="checked" value="nationalityAny" /> Div 1
<input name="rdoNationality" class="rdoNationality" type="radio" value="nationalitySelect" /> Div 2
<div id="nationalityAny">
Div 1 Selected
</div>
<div id="nationalitySelect" style="display:none;">
Div 2 Selected
</div>
的jQuery
$(function(){
$(".rdoNationality").on("click", function(){
var valNationality = $(this).val(),
divNationality = $("#" + valNationality);
$("div").hide();
divNationality.show();
});
});
但是当我在我的页面上尝试它时它不起作用(注意:我确定我的jQuery路径是正确的)。这是我的完整HTML
<!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>
<title>Title Here</title>
<meta name="keywords" content="kw here" />
<meta name="content-language" content="en" />
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$(".rdoNationality").on("click", function(){
var valNationality = $(this).val(),
divNationality = $("#" + valNationality);
$("div").hide();
divNationality.show();
});
});
</script>
</head>
<body style="background:#fff;">
<div>
<input name="rdoNationality" class="rdoNationality" type="radio" checked="checked" value="nationalityAny" /> Div 1
<input name="rdoNationality" class="rdoNationality" type="radio" value="nationalitySelect" /> Div 2
<div id="nationalityAny">
Div 1 Selected
</div>
<div id="nationalitySelect" style="display:none;">
Div 2 Selected
</div>
</div>
</body>
</html>
我的代码出了什么问题。感谢。
答案 0 :(得分:0)
更好地添加在线jQuery CDN版本,如
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
对于收音机和复选框,更改也是更好的事件。所以试试这个
$(function(){
$(".rdoNationality").on("change", function(){
var valNationality = $(this).val(),
divNationality = $("#" + valNationality);
$("div").hide();
divNationality.show();
});
});
检查此原始JSfiddle
答案 1 :(得分:0)
问题在于选择器$("div").hide();
,
这将隐藏文档中的所有div。
答案 2 :(得分:-1)
你缺少document.ready function ...意思是在页面
之后所有的dom元素都被载入了<script type="text/javascript">
$(document).ready(function(){
$(".rdoNationality").on("change", function(){
var valNationality = $(this).val(),
divNationality = $("#" + valNationality);
$("div").hide();
divNationality.show();
});
});
</script>