如何让多个在同一个网页上添加另一个字段而不会相互影响?

时间:2015-11-15 19:28:16

标签: javascript jquery

我尝试将以下所有三个功能组合在一起,当用户点击add-another按钮时添加一个新字段,但我不想让每个功能在每个按钮位于同一网页时相互影响clicked有一种方法可以将每个功能组合在一起,每个功能都影响同一网页上的不同表单字段。

JQuery的

$(document).ready(function(){
    $('.add-another').click(function(e){
        e.preventDefault();
        $(this).closest('li').find('div:eq(3)').prepend('<select name="drop_down" class="color"><option value="red" selected="selected">Red</option><option value="blue">Blue</option></select>');
    });
});

$(document).ready(function(){
    $('.add-another').click(function(e){
        e.preventDefault();
        $(this).closest('li').find('div:eq(0)').prepend('<label class="food"><input type="text" name="food[]" /></label>');
    });
});

$(document).ready(function(){
    $('.add-another').click(function(e){
        e.preventDefault();
        $(this).closest('li').find('div:eq(0)').prepend('<label class="candy"><input type="text" name="candy[]" /></label>');
    });
});

1 个答案:

答案 0 :(得分:0)

好的,没有理解原来的问题。您希望一个函数检查单击了哪个按钮,然后根据按钮执行不同的操作。下面的代码假定每个按钮都有自己的ID(button1,button2,button3)。

$('.add-another').click(function(e){
     e.preventDefault();
     switch($(this).prop('id')){
         case 'button1':
              //some code for the first button;
              $(this).closest('li').find('div:eq(3)').prepend('<select name="drop_down" class="color"><option value="red" selected="selected">Red</option><option value="blue">Blue</option></select>');
              break;
         case 'button2':
              //some code for the second button;
              $(this).closest('li').find('div:eq(0)').prepend('<label class="food"><input type="text" name="food[]" /></label>');
              break;
         case 'button3':
              //some code for the third button;
              $(this).closest('li').find('div:eq(0)').prepend('<label class="candy"><input type="text" name="candy[]" /></label>');
              break;
     }
     return false;
})