我寫了一個小腳本,它應該根據活動的複選框更改URL。這裏的'問題'是有特殊情況,當href是'一,二,三'時,變量'one'和'two'有一個逗號,但如果只複選'two'複選框,那麼href也應該只是兩個'沒有逗號。我通過切片功能或多或少地工作。根據複選框更改href
有沒有更好的方式來寫在一個函數中,並保存x行代碼?
DEMO:http://jsfiddle.net/UKD2m/
var one ="111,";
var two ="222,";
var three ="333";
$('body').append('<a href=\"' + one + two + three + '\">link</a>'); //this is the default value
$('.checkbox').change(function() {
if ($('#one').is(':checked')) { // one only + slice out last character (comma)
$("a").attr("href", one.slice(0,-1));
}
if ($('#one').is(':checked') && $('#two').is(':checked')) { //one and two
$("a").attr("href", one + two);
}
if ($('#one').is(':checked') && $('#three').is(':checked')) { //one and three
$("a").attr("href", one + three);
}
if ($('#two').is(':checked')) { // two only + slice out last charachter (comma)
$("a").attr("href", two.slice(0,-1));
}
if ($('#two').is(':checked') && $('#three').is(':checked')) { // two and three
$("a").attr("href", two + three);
}
if ($('#three').is(':checked')) { // three only
$("a").attr("href", three);
}
if ($('#one').is(':checked') && $('#two').is(':checked') && $('#three').is(':checked')) { // three only
$("a").attr("href", one + two + three);
}
});
爲什麼不在複選框上設置一些數據並使用javascript連接函數?所有這些條件將不會被需要 – AndreDurao
是你的代碼工作正常嗎? –