如何进一步增强此代码?

时间:2017-01-19 12:31:23

标签: javascript jquery

 $( document ).ready( function() {

    var dynamicChargableForm = 1;
    var dynamicDiscountForm = 1;

    var selectedId = 1;
    var newTextarea = null;

    var chargableHeader = document.getElementById( 'chargable-header' );
    var disountHeader = document.getElementById( 'discount-header' );

    var execute = null;

    $(document).on('keyup','.dynamic',function() {

       var typeName = this.id.split('-')[0];

       switch( typeName ) {

       case 'chargable':
             execute = dynamicRow( this, 'chargable', dynamicChargableForm , chargableHeader );
             execute ? dynamicChargableForm++ : execute = null;
             break;

       case 'discount' :
             execute = dynamicRow( this, 'discount', dynamicDiscountForm, disountHeader );
             execute ? dynamicDiscountForm++ : execute = null;
             break;
       }
    });
  });

  function dynamicRow( element, type , relatedTracker , relatedHeader )
  { 
     selectedId = element.id.split('-')[1];

     if ( selectedId == relatedTracker ) 
     {
        relatedTracker++;

        newTextarea = document.createElement( 'TEXTAREA' );
        newTextarea.setAttribute( 'name', type + '-' + relatedTracker );
        newTextarea.setAttribute( 'class' , 'form-control dynamic ' + type );
        newTextarea.setAttribute( 'id' , type + '-' + relatedTracker );

        relatedHeader.append( newTextarea );

        return true;
    }

    return false;
  }

这是我第一次尝试在最后添加的表单上添加用户输入时动态填充textarea。我想对我的代码提出建议和评论,因为我认为这段代码效率不高。我想从专家那里获得更好的理解和立场。

谢谢

1 个答案:

答案 0 :(得分:0)

替换

         execute = dynamicRow( this, 'chargable', dynamicChargableForm , chargableHeader );
         execute ? dynamicChargableForm++ : execute = null;

通过

         if(dynamicRow( this, 'chargable', dynamicChargableForm , chargableHeader )) {
           dynamicChargableForm++;
         }

我不知道你为什么需要添加动态名称。最好的方法是将名称设置为chargable[]。然后该字段将作为数组发送到服务器。