.each函数导致附加问题

时间:2013-07-14 03:27:21

标签: jquery each

我正在尝试读取给定输入名称的列表,然后检查DIV中跨度名称的那些输入名称。使用以下代码会导致复制问题..

$('.right').find(':input').each(function(){
       $(this).change(function(){
       var class_name ='';
       class_name = $(this).attr('name');  

       $('#specs').find('span').each(function(){ 

       if(class_name == $(this).attr('name')){
       //Update the current span with the information from input.

       }else{
       //Add span with class information  
       $('#specs').append("<span name='"+class_name+"'>"+class_name+"</span>");

       }

       });
  });

});

似乎发生的事情是每次添加跨度时,添加的下一个跨度都会添加+之前的跨度。

所以...

如果您在单击下一个输入字段时已经有5个跨度,则会添加11个跨度....而不仅仅是一个。

为什么会这样?

任何帮助都会很棒!

2 个答案:

答案 0 :(得分:0)

$(this).change(function(){

应为$('.right :input').change(function(){

你应该删除

$('.right').find(':input').each(function(){一起。

答案 1 :(得分:0)

试试这样:

$('.right :input').on('change', function() {
    if ( $('span[name="'+ this.name +'"]').length ) { // span already exists
        $('span[name="'+ this.name +'"]').text(this.value);
    } else {
        var span = $('<span />', {name:this.name, text:this.value});
        $('#specs').append(span);
    }
});