【发布时间】:2015-05-17 02:48:54
【问题描述】:
此题不重复。
我有两个单选按钮(radio1、radio2)。
我能够分别实现以下目标:
- 在页面加载时触发点击“radio1”。因此,无论何时加载页面,都会单击该按钮。
- 记住用户手动单击的选定单选按钮,使用 Joseph Silber 在this answer 中描述的本地存储。因此,如果用户手动单击“radio2”然后刷新页面,它会记住该选择。
问题是我不能同时使用这两种方法。因为触发的点击总是占用本地存储,导致页面刷新时不记得选中的单选按钮。
默认情况下,我需要在页面加载时单击(未选中)“radio1”,但是当用户手动单击“radio2”时,它会记住该选择,并且每当刷新页面时,都会单击“radio2”尊重用户的选择。
我尝试了很多方法来组合代码,我必须让它们一起工作,但我无法弄清楚。
页面加载时触发点击单选按钮的代码:
<script type="text/javascript">
$(document).ready(function() {
$("#radio1 input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
</script>
本地存储的代码;记住电台选择:
<script type="text/javascript">
$(function()
{
$('input[type=radio]').each(function()
{
var state = JSON.parse( localStorage.getItem('radio_' + this.id) );
if (state) this.checked = state.checked;
});
});
$(window).bind('unload', function()
{
$('input[type=radio]').each(function()
{
localStorage.setItem(
'radio_' + this.id, JSON.stringify({checked: this.checked})
);
});
});
</script>
同样,它们都可以正常工作,但单独使用,其中任何一个都可以工作。
如果有人可以帮助我使这两种方法一起工作,我将不胜感激。
【问题讨论】:
标签: javascript php jquery html radio-button