2016-04-25 22 views
0
$(parentQuestion.children('.choice_class:last')); 
<div class='parentquestion'> ..... 
<div class="choice_class"> 
      <div class="form-group"> 
       <label class="control-label col-md-3 col-sm-3 col-xs-12"><span class="choice-no">Option 1</span><span class="required">*</span> 
       </label> 
       <div class="col-md-6 col-sm-6 col-xs-12"> 
        <input type="text" required="required" class="form-control col-md-7 col-xs-12"> 
       </div> 
       <a href="javascript: void(0);" onclick="addOption(this)" class="btn btn-danger"><span class="glyphicon glyphicon-plus"></span>Add Choice</a> 
      </div> 
     </div> 

inside addOption関数この変数を使用して、親オブジェクトを見つけて最後の.choice_classの下に別のオプションを追加しました。Jquery子供の子供elemnt

2番目のオプションを追加すると、オプション1をオプション2に変更する必要があります。

完全な機能が

function addOption(that) { 
     $(that).parent().parent().after($('.choice_class_sample .choice_class').clone()); 

     var parentQuestion = $(that).parent().parent().parent(); 
     var lastChoice = parentQuestion.children('.choice_class:last'); 

     $(parentQuestion.children('.choice_class:last-child .choice-no')).html(parentQuestion.children('.choice_class').length); 
     $(that).remove(); 
    } 

あるしかし、私は子供を選択した後、さらにより選択することはできませんよ。

答えて

2

あなたのコードを「動作させる」ように修正することができますが、これはちょっとしたことです。すなわち、複製する前に既存の要素をコピーするのにcloneを使用します。

DOMのJavaScriptデータ構造(配列のようなもの)を表現し、それらを同期させたい場合は、テンプレートシステムを使用する方がはるかに良いでしょう。あなたがjQueryを使用しているので、jQuery Template pluginはまともでないようです。 READMEをスキミングから、それはこのように自分のものには同じくらい簡単になるだろう:

var options = [ { id: 1 } ] 

parentQuestion.loadTemplate("#template", questions) 

$('.add-choice-button').on('click', function() { 
    options.push({ 
    id: options.length + 1 
    }) 

    parentQuestion.loadTemplate('#template', options) 
}) 

多く、非常にクリーン:

<script type="text/html" id="template"> 
    <div> 
    <div> 
     <label> 
     <span>Option <span data-content="id"></span></span> 
     <span class="required">*</span> 
     </label> 

     <div> 
     <input type="text" required="required"> 
     </div> 

     <a href="#" class="add-choice-button"><span class="glyphicon glyphicon-plus"></span> Add Choice</a> 
    </div> 
    </div> 
</script> 

次に、あなたのJavaScriptで、あなたのような何かを持っていると思います。そして、何よりも、あなたのJSで醜い必須のDOM操作を避けることができます。

+0

アドバイスをいただきありがとうございます。それは清潔できれいに見えます。私は複数の質問があることを言及する必要があります。すべての質問には独自のオプションがあります。 – Mahesh

+0

私のコーディングでは、find()を使用して問題を解決しました。しかし、私はあなたがアドバイスしたとおりにそれらを変更しています。ありがとう – Mahesh