2013-01-12 185 views
2

我有一個jQuery的,將項目添加到選擇列表,並更改背景顏色,以表明它已被添加(選擇列表不可見)。當我點擊加號時,它將項目添加到列表中並將背景更改爲綠色。當我再次單擊它時,它將刪除項目和顏色。這工作一次。如果我重複這個循環,它將停止工作。任何想法,爲什麼這可能是?添加/刪除多選jquery選項

<ul> 
<li><span id='add'> + </span>this is a test 
</li> 
</ul> 
<select multiple="multiple" id="destination"></select> 

$(document).ready(function() { 
    $("#add").click(function() { 
var color = $("#add").css("background-color"); 
if (color == "transparent") { 
    $("#add").css("background-color", "green"); 
    $("#destination").append('<option value="1">New option</option>'); 
} else { 
    $("#add").css("background-color", "transparent"); 
    $("#destination option[value='1']").remove(); 
} 
}); 
}); 

回答

3

這取決於瀏覽器。例如在Chrome $("#add").css("background-color")中返回rgba(0,0,0,0)而不是transparent。因此,像這樣讀取背景顏色並不是跨瀏覽器兼容的。

一般來說,我認爲你可能會更好的班級。

http://jsfiddle.net/watRq/

$(document).ready(function() { 
    $("#add").click(function() { 
    if ($(this).hasClass("transparent")) { 
     $(this).addClass("green").removeClass("transparent"); 
     $("#destination").append('<option value="1">New option</option>'); 
    } else { 
     $("#add").addClass("transparent").removeClass("green"); 
     $("#destination option[value='1']").remove(); 
    } 
    }); 
}); 
3

不要爲背景檢查,只使用.toggle() event

http://jsbin.com/unojap/4/edit

$("#add").toggle(function() { 

     $("#add").css("background-color", "green"); 
     $("#destination").append('<option value="1">New option</option>'); 

    },function(){ 
     $("#add").css("background-color", "transparent"); 
     $("#destination option[value='1']").remove(); 

    }); 
1

不是檢查背景顏色,使用jQuery.data爲存儲元件是否已被添加或不:

var added = $(this).data("added"); 
// returns undefined if requested data does not exist 
if (!added) { 
    $(this).data("added", true); 
    // change background, do stuff 
} 
else { 
    $(this).removeData("added"); 
    // change background, do stuff 
} 

Demo