【发布时间】:2017-02-21 20:46:52
【问题描述】:
我想要实现的是:
- 页面的默认状态 = 未勾选复选框,未显示链接
- 用户勾选一个(或多个)复选框
- 显示链接,从复选框值动态生成,格式如下:http://example.com/?subject=Products&checked=Blue,Green,Purple(其中选中的复选框值为“蓝色”、“绿色”和“紫色”)
到目前为止,根据另一个问题 (Using JavaScript to load checkbox Values into a string) 的建议,我已经能够通过按钮以正确的格式(作为所需 url 的一部分)将值打印到 console.log:
$("button").on("click", function(){
var arr = []
$(":checkbox").each(function(){
if($(this).is(":checked")){
arr.push($(this).val())
}
})
var vals = arr.join(",")
var str = "http://example.com/?subject=Products&" + vals
console.log(str)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" id="selected" name="selected" value="Blue" class="products"> Blue<br>
<input type="checkbox" id="selected" name="selected" value="Green" class="products"> Green<br>
<input type="checkbox" id="selected" name="selected" value="Purple" class="products"> Purple
<br>
<button>button</button>
但是,它们不会根据选中的复选框动态加载(它需要您按下按钮才能生成 url)并且链接尚未打印到页面以供访问者使用(它卡在console.log,可见但不可用)。
我被告知.change() 可能是这里的方式,就动态生成链接而言。比如:jQuery checkbox change and click event。
如何合并这两种方法以达到我想要的结果?
【问题讨论】:
-
请注意,您的 html 中重复的
id="selected"无效。 ID 必须是唯一的 :)
标签: javascript jquery checkbox hyperlink