[英]jQuery / Javascript - else if statement not reaching else if
[英]If else statement not reaching the else part
因此,我正在制作一個可以在兩個圖像之間切換的圖像切換功能。 更具體地說,它切換div的背景圖像。
我正在使用jquery .data()函數作為計數器,其中一個=第一張圖片,兩個=切換圖片。
這是我正在使用的算法:
好像在第一次嘗試中替換了該圖像,就像在第一次“ if”中一樣,但是它並沒有在第二次嘗試中再次替換該圖像(其他部分)。 即使第一個if應該返回false然后轉到else,它似乎也永遠不會到達else部分。
任何幫助將不勝感激。 另外,我知道有一個.toggle()函數和其他圖像切換方法,但是我必須使用此方法,因為這只是較大程序中的一小塊經編輯的塊。
這是代碼:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="mouseovertestlayout.css" />
<script>
function startEdit()
{
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}
</script>
</head>
<body>
<div class="container" data-kangaroo="one" ></div>
<button onclick="startEdit()"> </button>
</body>
</html>
這是我的.css
.container
{
width: 20px;
height: 20px;
line-height: 0;
border-style:solid;
border-width:1px;
border-color:red;
padding: 20px;
background-repeat:no-repeat;
background-image:url('image1.png');
}
您的“其他”第一行中有錯別字是(this)
缺少的$
您在else子句中缺少$。
固定:
function startEdit() {
$("div").click(function ()
{
if (($(this).data('kangaroo')) == "one")
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)");
$(this).data('kangaroo',"one");
}
});
}
這樣嘗試
if (($(this).attr("data-kangaroo")) == "one") //Here is the edit
{
$(this).css('background-image', "url(image2.png)");
$(this).data('kangaroo',"two");
}
else
{
$(this).css('background-image', "url(image1.png)"); //Here put "$" before (this)
$(this).data('kangaroo',"one");
}
如果您使用class和toggleClass
可以做的事情要短得多。
演示: http : //jsbin.com/anazoq/1/edit
HTML:
<div class="container"></div>
<button>Toggle</button>
CSS:
div {
...
background: url(image1.png) no-repeat;
}
.switch {
background-image: url(image2.png);
}
JavaScript的:
$('button').click(function() {
$('div').toggleClass('switch');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.