我正在尝试了解如何使用firebug来调试我的Javascript。所以我有下面列出的HTML。我想在var's'上设置一个监视表达式。我转到Firebug的脚本选项卡并打开观看窗格并在 s 中输入“新观看表达式< /强>”。
我收到错误:
ReferenceError: s is not defined
为什么?
<!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>
<style type="text/css">
.StateOne .InitiallyHidden { display: none; }
.StateTwo .InitiallyVisible { display: none; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('.x').click(function() {
var s = $("#StateContainer")[0];
s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
});
});
</script>
</head>
<body>
<button class="x">Change StateContainer</button>
<div class="StateOne" id="StateContainer">
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
<div class="InitiallyVisible">Visible first</div>
<div class="InitiallyHidden">Visible second</div>
</div>
</body>
</html>
答案 0 :(得分:6)
变量's'仅在'x'的单击处理程序中定义,因为它是在函数内声明的。如果在点击功能中设置断点,则's'将起作用。
创建全局变量通常不是好习惯,但是为了调试,你可以通过在$(document).ready()函数之外声明它来使's'成为一个全局变量,如下所示:
<script language="javascript" type="text/javascript">
var s;
$(document).ready(function()
{
$('.x').click(function() {
s = $("#StateContainer")[0];
s.className = (s.className == 'StateOne' ? 'StateTwo' : 'StateOne');
});
});
</script>