【问题标题】:How to add new div tag when check box is checked using jquery使用jquery选中复选框时如何添加新的div标签
【发布时间】:2009-07-30 05:28:54
【问题描述】:

如何在选中复选框时添加新的 div 标签 在复选框旁边以及选中两个复选框时必须显示两个 div 标签。请帮助并让我使用 jquery 解决这个模块

【问题讨论】:

    标签: jquery html checkbox add checked


    【解决方案1】:
    $(':checkbox').click(function () {
        if ($(this).attr('checked')) {
            // create new div
            var newDiv = $('<div>contents</div>');
    
            // you can insert element like this:
            newDiv.insertAfter($(this));
    
            // or like that (choose syntax that you prefer):
            $(this).after(newDiv);
        } else {
            // this will remove div next to current element if it's present
            $(this).next().filter('div').remove();
        }
    });
    

    如果您不想在复选框标签旁边添加这个新的 div,那么首先确保您为复选框设置了 id,并使用标签中的 for 属性将标签与复选框连接起来:

    <label for="myCb1">test</label>
    <input type="checkbox" id="myCb1" value="1" />
    

    现在你可以稍微修改一下上面的JS代码,你就完成了:

    $(':checkbox').click(function () {
        // current checkbox id
        var id = $(this).attr('id');
    
        // checkbox' label
        var label = $('label[for=' + id + ']');
    
        if ($(this).attr('checked')) {
            // create new div
            var newDiv = $('<div>contents</div>');
    
            // insert div element
            newDiv.insertAfter(label);
        } else {
            // this will remove div next to current element if it's present
            label.next().filter('div').remove();
        }
    });
    

    【讨论】:

    • 嗨朋友,我使用了这段代码,但是当复选框被选中时,复选框本身隐藏了请帮忙
    • 我认为这可能是 CSS 问题,因为上面的代码运行正常。我为大家准备了一个小demo:stuff.rajchel.pl/stackoverflow/checkboxtest.html 不看代码很难说是哪里出了问题。
    • 感谢它正在工作,我唯一需要在复选框标签旁边显示那些 div 标签而不是在复选框之前
    • 如果您为复选框分配了 ID,并且您使用标签中的属性来匹配它们,那么修改代码来处理它非常简单。我会更新我的答案来告诉你。
    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2016-07-15
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多