javascript - 使用关闭按钮取消选中复选框

标签 javascript jquery html checkbox

请指教。 我想在容器标记复选框内添加标签,并通过单击每个标签的“x”按钮删除标签。 一切正常,除了当您单击“x”按钮并删除标签时,复选框的状态保持选中状态。 但我需要当您单击每个标签的按钮时,必须取消选中复选框的状态。

使用输入的值和名称可能更容易,但我不能使用它们 - 只能使用 id。

$(document).ready(function() {
        var $list = $("#itemList");

    $(".chkbox").change(function() {
        var a = $('label[for="' + this.id + '"]').text();
            if (this.checked) {
        $list.append('<li><a href="#">'+a+'</a><button class="closebutton" value="'+a+'">X</button></li>');
        }
        else {
            $("#itemList li:contains('"+a+"')").remove();
        }
    })
    $(document).on('click','.closebutton',function(){
       var b = this.value;
       $("#itemList li:contains('"+b+"')").remove();
        $('label[for="' + this.id + '"]').removeAttr('checked');        
        });
    });

    <div id="items">
        <ul id="itemList">
        </ul>
    </div>
    <div id="tab1" class="tab-pane">
    <div id="ck-button"><label for="one"><input type="checkbox" id="one" class="chkbox"><span>First book</span></label> </div>
    <div id="ck-button"><label for="two"><input type="checkbox" class="chkbox" id="two"><span>  Second book</span></label> </div>
    </div>

最佳答案

尝试

$(document).ready(function () {
    var $list = $("#itemList");

    $(".chkbox").change(function () {
        var a = $(this).next().text();
        if (this.checked) {
            $('<li><a href="#">' + a + '</a><button class="closebutton" value="' + a + '">X</button></li>').appendTo($list).data('src', this);

        } else {
            $("#itemList li:contains('" + a + "')").remove();
        }
    })
    $(document).on('click', '.closebutton', function () {
        var $li = $(this).closest('li');
        $($li.data('src')).prop('checked', false);
        $li.remove();
    });
});

演示:Fiddle

关于javascript - 使用关闭按钮取消选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20014865/

相关文章:

javascript - 如何使用 jquery $.get 在查询字符串参数中传递 json

android - 打 'native vs html5'移动应用之战

php - 谷歌地图标记未在 Firefox 中显示

javascript - 如何在 Javascript/JQUery 中将返回的 JSON 对象整形为数组?

javascript - 从斜杠分隔的 URL 构建键/值对象

javascript - Jquery 动画滚动问题

jquery - 在 WordPress 中使用 ajax 下载文件

javascript - jwPlayer 在 IE8 中不工作

html - 滚动菜单的 Div 不会使用子元素调整其大小

javascript - 如何在分配变量的情况下使用jquery