我发现此代码用选中的复选框值替换了链接文本(=“显示”)。现在,我正在寻找将链接的URL本身添加/删除选中/未选中的值的代码。
function calculate() {
var arr = $.map($('input:checkbox:checked'), function(e, i) {
return +e.value;
});
$("[href$='feature=']").text('the checked values are: ' + arr.join(','));
}
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<div><a href="/best/?price=123&feature=">Show</a></div>
<a href="/best/?price=123&feature=Teamsport">Show</a>
非常感谢您的帮助,伙计们!
答案 0 :(得分:0)
此外,由于您希望更改href
...并且它与attribute selector一起使用,因此我将在href
更改之前将元素保存在变量中。与href
“基本”值本身相同。因为第二次点击,href
不会以feature=
结尾。
这是一个可行的演示:
function calculate() {
var arr = [];
$('input:checkbox:checked').each(function(i,v) {
arr.push(v.value);
});
// The array in console
console.log(arr);
// Join it has a string
var arr_string = arr.join(",");
// Use the string in the link's text AND the href
link
.text('the checked values are: ' + arr_string)
.attr('href', link_href_base + arr_string);
// The link's href in console
console.log(link.attr("href"));
}
// Variables that won't change
var link = $("[href$='feature=']");
var link_href_base = link.attr("href");
calculate();
$('div').delegate('input:checkbox', 'click', calculate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="options[]" value="Teamsport" />
<input type="checkbox" name="options[]" value="Individual sport" />
</div>
<div><a href="/best/?price=123&feature=">Show</a></div>