2017-06-24 28 views
0

誰もこれらの機能を簡単にすることができますか?フォームに数値を動的に入力してください

私はUL持っている:

<ul class="phone-type">   
     <li class="office" id="1"></li> 
     <li class="mobile" id="2"></li> 
     <li class="fax" id="3"></li>  
</ul> 

とJS:私はすべての李のためにそれをリセットする必要が

var o = 0;var m = 0;var f = 0; 
    $('ul.phone-type li.office').click(function() { 
     o++; 
     $('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+o+'" name="phone['+$(this).attr('class')+'-'+o+']" type="text" ><br>'); 
    }); 
    $('ul.phone-type li.mobile').click(function() { 
     m++; 
     $('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+m+'" name="phone['+$(this).attr('class')+'-'+m+']" type="text" ><br>'); 
    }); 
    $('ul.phone-type li.fax').click(function() { 
     f++; 
     $('.phones').append('<input class="form-control phone_type" placeholder="'+ $(this).text()+'-'+f+'" name="phone['+$(this).attr('class')+'-'+f+']" type="text" ><br>'); 
    }); 

を.. は、私はそれを簡単にすることができますどのような方法があります! !! tnx

+0

あなたは本当に望ましい行動が何であるかを説明していませんでした。 –

答えて

0

この方法では、不特定多数のクリック可能なリスト要素が許可されます。含まれるすべての要素に 'data-type'属性を指定するようにしてください。

html要素にデータを格納するときは、通常は 'data'属性を使用するのが最善です。クラスの使用は、クラスが1つしかない場合にのみ機能します。

HTML

<ul class="phone-type"> 
    <li data-type="office" id="1">office</li> 
    <li data-type="mobile" id="2">mobile</li> 
    <li data-type="fax" id="3">fax</li>  
</ul> 
<div class="phones"></div> 

JS

// This object will contain how many clicks each element has 
    var typeClicks = {}; 

    $('ul.phone-type li').click(function() { 
    var li = $(this), 
     type = li.data('type'), 
     text = li.text(), 
     clicks; 
    // check if typeClicks contains any click data for this element 
    if (typeClicks.hasOwnProperty(type)) { 
     // if it does, increases tracked clicks by one 
     typeClicks[type]++; 
     clicks = typeClicks[type]; 
    } else { 
     // if not, this will create an entry for this element 
     clicks = typeClicks[type] = 1; 
    } 
    // if not, this will create an entry for this element 
    $('.phones').append('<input class="form-control phone_type" placeholder="'+text+'-'+clicks+'" name="phone['+type+'-'+clicks+']" type="text" ><br>'); 
    }); 
+0

ありがとう..私はそれを得た.. – behzad

+0

うん、問題ない! –

関連する問題