javascript - 动态加载包含复选框的 test.php 时,复选框提醒脚本不记得复选框状态

标签 javascript jquery ajax checkbox dynamic-loading

我有一个有效的复选框提醒脚本:http://mauricederegt.nl/test/index.html

它只是记住复选框状态,因此当您稍后返回网页时,它仍然会被选中为未选中。这一切都很好。

现在我需要在 HTML 页面中动态加载一个 php 页面(原始 php 页面从我的数据库中获取一些内容并显示名称列表。在该列表下方,出现此复选框,后面是数据库中的另一个列表)。

我已将复选框放置在 php 文件中,但加载 php 文件时它将显示在 HTML 文件中。 js 文件仍然加载在 HTML 文件中(也尝试将其加载到 php 文件中,但这没有效果)。

问题:不再记住该复选框:(请参阅此演示:http://mauricederegt.nl/test/index2.html

我认为这是因为页面现在是动态加载的并且在 HTML 中不可见?

如何解决这个问题,以便再次记住该复选框?

如果需要,请查看 HTML 文件的源代码以获取 js 代码(内容太多,无法在此处发布)

亲切的问候,

PHP 代码:

   <?php  
$q=$_GET["q"];
$checked = ($_GET['checked'] == 1 ) ? 'checked="checked"' : '';

if ($q == 1) {
echo '<ul>
        <li>Mike</li>
        <li>Peter</li>
        <li>Richard</li>
        <li>Quintin</li>
        </ul>
<div id="soundcheck" class="button blue"><input type="checkbox" value="Name" id="sound" '.$checked.' /><label for="sound"></label></div>
<ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Pineapple</li>
        </ul>';
}
?>

最佳答案

问题在于,检查并设置复选框记住状态的代码仅在首次加载页面(绑定(bind)到 DOM 就绪事件)时调用,因此在动态加载内容时不会调用。

调用现有代码的这一部分:

$('div#soundcheck input:checkbox').each(function() {
    // on load, set the value to what we read from storage:
    var val = storedData.get(this.id);
    if (val == 'checked') $(this).attr('checked', 'checked');
    if (val == 'not') $(this).removeAttr('checked');
    if (val) $(this).trigger('change');
});

动态加载复选框后,应该可以解决问题。

编辑: 您需要将上述代码添加到现有 Javascript 的此部分:

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("scoreboard").innerHTML=xmlhttp.responseText;
        // add the above code here
    }
}

关于javascript - 动态加载包含复选框的 test.php 时,复选框提醒脚本不记得复选框状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10700075/

相关文章:

javascript - 返回 false 不停止表单提交

javascript - 防止子节点的 mouseout 事件

php - 当 JS 需要 PHP 变量时,如何将 javascript 与 PHP 分开?

jquery - 如何增加内圈的大小

javascript - 从内部局部 View 修改主视图

javascript - 即使在 php 中选择选项,也会在按钮单击时显示和隐藏 div

javascript - 绑定(bind)到 Polymer 中的全局变量

javascript - 使用逗号自动格式化数字时如何保留预期的光标位置?

javascript - 使用 JQuery 在 DIV 中选择一个元素

javascript - AJAX 加载的 JQuery 日期选择器仅在警报后工作