使用jquery产品配置器添加和删除文本行的最佳方法

时间:2012-10-30 21:51:09

标签: php javascript jquery codeigniter

我正在使用Jquery创建产品配置器。我的用户可以在其产品中添加自定义文本行。所以你可以用自定义文本创建说... 4文本行。

我需要知道添加和删除这些行的最佳方法是什么。目前我有以下代码添加行...

    //Add Text Button
$('a#addText').live('click', function(event) {
    event.preventDefault();

    //Scroll up the text editor
    $('.textOptions').slideUp();
    $('#customText').val('');

    //count how many items are in the ul textList
    var textItems = $('ul#textList li').size();
    var nextNumber = textItems + 1;

    if(textItems <= 5) {

        //Change input to reflect current text being changed
        $('input#currentTextNumber').val(nextNumber);

        //Append a UL Item to the textList
        $('ul#textList').append('<li id="textItem'+nextNumber+'">Text Line. +$5.00 <a class="deleteTextItem" href="'+nextNumber+'">Delete</a></li>');

        //Scroll down the text editor
        $('.textOptions').slideDown();

    }else {

        alert('you can have a maximum of 6 textual inputs!');   

    }
});

我可能不是最好的方式,但基本上我有一个空的UL列表开始。因此,当他们单击“添加文本行”时,它会找出无序列表中有多少列表元素,向其中添加值1,并放置一个新的列表元素,其中包含ID TextItem1或TextItem2或我们正在使用的任何数字。< / p>

我遇到的问题是当你点击删除项目时,它会搞砸所有内容,因为当你再次添加一个项目时,所有数字都不正确。我想写一些逻辑,说明你想要删除的数字之上的所有数字从它们的值中减去1,并且下面的所有数字都保持不变。但我认为我只是采取了错误的方式。

有关添加和删除这些文本行的最简单方法的任何建议都表示赞赏。

2 个答案:

答案 0 :(得分:2)

在你将要添加和删除随机ID的情况下尝试增加ID或类通常更令人头疼,而不是值得

更改为项目的单个班级

<li class="textItem">

您的删除视为

$('#textList').on('click','.textItem a', function(){/* note that live() is deprecated*/
      $(this).parent().remove();
      $('input#currentTextNumber').val( $('#textList li').length );/* note that size() is deprecated*/
      return false;
});

如果您在此过程中的任何一个服务器上都有任何其他动态数据存储或AJAX,则可能还有简单的方法来配置这些存储,并结合使用元素的公共类。

答案 1 :(得分:0)

这应该有帮助

编辑:显然,引用是我应该考虑的事情。 代码正在运行,但没有想要的参考。 好吧,然后用这个......

var currentIdx = $('ul#textList li').size();

$('a#addText').click(function(event) { 
    event.preventDefault();

    //Scroll up the text editor
    $('.textOptions').slideUp();

    //count how many items are in the ul textList
    var nextNumber = currentIdx++;

    if($('ul#textList li').size() <= 5) {

        //Change input to reflect current text being changed
        $('input#currentTextNumber').val(nextNumber);

        var newLi = $('<li class="textItem' + nextNumber + '">' + 
            $('#customText').val() +
            '<a class="deleteTextItem" href="#">Delete</a></li>');

        newLi.find('a.deleteTextItem').click(function() {
            $(this).parent('li').remove();
        })

        //Append a UL Item to the textList
        $('ul#textList').append(newLi);

        $('#customText').val('');

        //Scroll down the text editor
        $('.textOptions').slideDown();

    } else {
        alert('you can have a maximum of 6 textual inputs!');   
    }
});​

这是fiddle