Jquery在追加和删除之间切换不按预期工作

时间:2013-07-27 07:12:57

标签: jquery

追加和删除之间的以下切换不起作用:

$('.t').click(function() {
            var className = $(this).data('class');
            $(this).toggleClass(className).toggleClass(className+'1');

            var newTable='<table style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>';
            $("#newDiv").append(newTable).remove(newTable);
        });

HTML

 <div class="t a" data-class="a"> 8cghfghfghfghfg</div>
 <div class="t b" data-class="b">20cghfghfghfghfg</div>
 <div class="t c" data-class="c"> 4cghfghfghfghfg</div>

 <div id="newDiv"></div>

Working Demo Here..

在这里,我想要做的是..如果我点击div.t,我想删除特定的类(例如:.a)并添加相应的类(例如.a1),这是我实现的。 / p>

但是我想在第一次点击时添加一个表,想要在第二次点击时删除该添加的表。

我怎样才能实现这一目标,请任何人帮助我......

由于

2 个答案:

答案 0 :(得分:4)

要切换追加和删除,您可以使用被点击元素的data属性。它更清洁:

    $('.t').click(function () {
        //general stuff must happen everytime class is clicked
        //get the className from data- attr
        var className = $(this).data('class');
        //toggling to change color
        $(this).toggleClass(className).toggleClass(className + '1');

        //check if its clicked already using data- attribute
        if ($(this).data("clicked")) {
            //remove it if yes
            $("#newDiv").find("#tablefor-" + className).remove();
        } else {
            //new table - note that I've added an id to it indicate where it came from
            var newTable = '<table id="tablefor-' + className + '" style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1' + className + '</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>';

            //append table                
            $("#newDiv").append(newTable);
        }
        //reverse the data of clicked
        $(this).data("clicked", !$(this).data("clicked"));
    });

演示:http://jsfiddle.net/hungerpain/m9ak9/11/

答案 1 :(得分:0)

只需使用if开关来确定表格是否已存在。我修改了你的小提琴以证明这一点: http://jsfiddle.net/m9ak9/6/

我在表格中添加了id以便识别,但您也可以使用以下内容查找:

var findTableInDiv = $('#newDiv').find('table');