所以简而言之,我想做的是在特定元素的点击事件上,即(.beanHolder ul li)我想从分数(.score)中减去然后声明一个变量(clicked =“yes”)那么当用户再次单击该项目,代码的第二部分被处理。我知道冗长的方法是为每个 .bean 声明一个 var(这将是至少 40 个 var),因此代码可能会变得相当冗长。我的想法是,我可以使用“this”将变量添加到 bean,但实际上它不起作用。任何想法都会很棒!!!
我的 jQuery 代码 ->
<script>
$(document).ready(function(){
var clicked = "";
$(".beanHolder ul li").click(function(){
if (this.clicked == "")
{
$(".bean", this).attr("src", "img/bean.png");
var number = parseInt($('#score').text());
number-=1;
$('#score').text(number);
this.clicked = "yes";
return;
}
else if (this.clicked == "yes")
{
$(".bean", this).attr("src", "img/beanG.png");
var number = parseInt($('#score').text());
number+=1;
$('#score').text(number);
this.clicked = "";
return;
}
});
});
</script>
编辑:我让它工作了;如果有人正在寻找类似的东西,这将起作用->
<script>
$(document).ready(function(){
$(".beanHolder ul li").click(function(){
//$(this).data("clicked","no");
var clicked = $(this).data("clicked");
if (clicked)
{
$(".bean", this).attr("src", "img/beanG.png");
var number = parseInt($('#score').text());
number+=1;
$('#score').text(number);
$(this).data("clicked",false);
//var clicked = $(this).data("clicked");
//return;
}
else
{
//This is to keep the score from going below 0; as it is it can not go over a score of 20.
if (parseInt($('#score').text()) > -1)
{
$(".bean", this).attr("src", "img/bean.png");
var number = parseInt($('#score').text());
number-=1;
$('#score').text(number);
$(this).data("clicked",true);
//return;
}
}
});
});
</script>