我写了一个小脚本,它应该根据哪些复选框处于事件状态来更改 URL。这里的“问题”是有特殊情况,当 href 为“一,二,三”时,变量“一”和“二”有逗号,但如果仅选中复选框“二”,则 href 也应该只是是“二”,不带逗号。我或多或少可以通过切片函数来实现这一点。
是否有更好的方法可以在函数中编写此代码并节省 x 行代码?
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);
}
});
最佳答案
如果您可以的话,我肯定会从复选框选项的 value
属性中驱动 href
值。首先,您必须设置复选框以使其具有关联的值:
<input class="checkbox" id="one" type="checkbox" checked value="111">one<br />
<input class="checkbox" id="two" type="checkbox" checked value="222">two<br />
<input class="checkbox" id="three" type="checkbox" checked value="333">three<br />
如果可能的话,我也会继续在 HTML 中默认链接:
<a href="111,222,333">link</a>
然后,您可以减少 JS,这样,每次更改其中一个复选框时,它都会查看该组,识别当前选中的复选框,然后将这些选定复选框的值连接到单个字符串中:
$(document).ready(function() {
$('.checkbox').on("change", function() {
var aHrefVals = [];
$('.checkbox').filter(":checked").each(function() {
aHrefVals.push($(this).val());
});
$("a").attr("href", aHrefVals.join(","));
});
});
关于javascript - 根据复选框更改 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298677/