如何在 jquery 中添加 js var
How to add js var inside jquery
不知何故,我无法使var"转向"更改。
--------------'#a3'是一个div-----------------
对于所有代码,请转到此处。
以下是一些 js/jquery:
var turn = 1;
if (turn === 1) {
//----------------------------red
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "red");
turn = 0;
});
}
if (turn === 0) {
//----------------------------blue
if (da3 === false) {
$('#a3').click(function () {
$(this).css("background-color", "blue");
turn = 1;
});
}
这是我使用的一些 css:
div {
display: inline-block;
background-color:grey;
width : 150px;
height: 150px;
}
这是因为您只添加一个只做一件事的事件处理程序。它不会神奇地添加另一个。
在点击事件中执行 if/else 逻辑。
如果要
通过单击 a3 元素来切换背景颜色,则需要在事件处理程序内部执行 if/else 检查:
bg_state = 0;
$('#a3').click(function () {
if (bg_state===0) {
$(this).css("background-color", "blue");
bg_state=1;
} else {
$(this).css("background-color", "red");
bg_state=0;
}
});
http://jsfiddle.net/ADUV9/
事件处理程序的设置仅在页面加载时执行一次!
您当前的代码结构如下:
var turn = 1; // red turn first
if (turn === 1) {
// assign click handlers for red moves
}
if (turn === 0) {
// assign click handlers for blue moves
}
这样做的问题是,这里唯一将使用的点击处理程序是在if (turn === 1)
块中定义的那些。 修改turn
时不会重新评估代码,因此永远不会使用蓝色的单击处理程序。
相反,它应该看起来像这样:
var turn = 1; // red turn first
// example click handler:
$('#a3').click(function () {
// check whose turn it is *inside* of the click handler
if (turn === 0) {
$(this).css("background-color", "blue");
turn = 1;
} else {
$(this).css("background-color", "red");
turn = 0;
}
});
// other click handlers like the above (or better yet, reuse the same function)
相关文章:
- 向AngularJS目录添加JS变量
- 使用 Razor 添加 JS 代码
- 在运行时添加js文件时出现语法错误
- 如何根据窗口宽度添加js文件
- 在Cordova项目中添加.js会破坏构建过程
- 动态添加 js 到 asp.net 文件
- 添加JS时Tumblr的奇怪行为
- 如何使用 api 修改 bigcommerce 前端(在应用程序中添加 js 代码)
- 是否可以阻止requireJS自动添加.js文件扩展名
- require.js文本插件在文件名中添加“.js”
- 如何在 jquery 中添加 js var
- 在Joomla head上添加JS
- 双击和更新表字段时添加 JS/添加文本框
- 在服务器的html文件中添加.js文件作为源文件
- 在另一个文件中添加JS src
- 最早什么时候可以动态添加JS/CSS并应用它们
- 如何在eclipse中添加JS资源
- 不能添加JS文件,或任何其他,到钛项目文件夹
- ASP.. NET在页面加载时添加js文件
- 如果主体类有类添加js,如果没有添加这个js