我有一個選擇下拉列表有兩個選項:是/否(實際上是三個:也有「選擇一個選項」沒有值)。 然後有一些chekboxes處理一些變量(當檢查變量被添加到一個全局變量(稱爲tot),當unckecked他們被扣除)。我希望有兩種不同的複選框行爲,具體取決於下拉選項是「是」還是「否」。所以我寫了這個,但我認爲我誤解/誤認了某些東西,因爲它不起作用(它不是嵌套在更改選擇功能中時起作用)。如何在jQuery中嵌入更改函數內的點擊函數?
<select name="container" id="container">
<option id="none" value="" >Select an option</option>
<option id="no" value="no" >no</option>
<option id="yes" value="yes" >yes</option>
</select>
而這裏的JavaScript(用jQuery庫)
var tot = 0;
$(document).ready(function() {
$("#container").change(function() {
var sel = $(this).find(":selected").attr("id")
if (sel == "no" || sel == "none") {
$("#in-category-1").click(function() {
if ($('#in-category-1').is(':checked')) {
if (tot < 60) {
tot = tot + 2.5;
} else if (tot >= 60) {
alert('Stop!');
$('#in-category-1').attr('checked', false);
}
} else if (tot > 0) {
tot = tot - 2.5;
}
functionblablabla();
});
if (sel == "yes") {
$("#in-category-1").click(function() {
if ($('#in-category-1').is(':checked')) {
if (tot < 50) {
tot = tot + 2.5;
} else if (tot >= 50) {
alert('Stop!');
$('#in-category-1').attr('checked', false);
}
} else if (tot > 0) {
tot = tot - 2.5;
}
functionblablabla2();
});
});
});
即使選項默認情況下,在頁面加載選擇應該發生某件事(選項存儲在數據庫中),因此如果沒有被選中同樣的事情應該發生
if (($('#no').prop('defaultSelected')) || ($('#none').prop('defaultSelected'))) {
$("#in-category-1").click(function() {
//same stuff than change select no or select none
});
}
if ($('#yes').prop('defaultSelected')) {
$("#in-category-1").click(function() {
//same stuff than change select yes
});
}
我做錯了什麼?
我不認爲你需要那種複雜的嵌套。您只需在點擊時檢查各種輸入的狀態以確定操作。 – isherwood 2013-02-15 18:32:18
你的意思是,在點擊功能中,我檢查選擇選項是yes還是no? – 2013-02-15 18:33:54
也許。我只看了你的代碼一分鐘,但這聽起來是對的。 – isherwood 2013-02-15 18:35:19