2014-02-21 2 views
0

У меня возникли трудности, на мой насыпью сохранить/добавить ..Как я могу получить доступ к дочернему элементу дочернего элемента? это возможно?

вот мой код

<div id="contentMain"> 
    @using (Html.BeginForm("ClientCustomerPositionSkillSave", "Customer", FormMethod.Post, new { id = "clientcustomerPositionSkillForm" })) 
    { 
     <input type="hidden" id="clientCusPosSkillId" name="clientCusPosSkillId" value="" /> 
     <input type="hidden" id="clientCusPosId" name="clientCusPosId" value="@clientCusPosId" /> 
     <input type="hidden" id="clientCusId" name="clientCusId" value="@clientCusId" /> 
     <input type="hidden" id="clientId" name="clientId" value="@clientId" /> 

     <h2> 
      Add Customer Position Skill</h2> 
     <div class="main"> 

     <div id="optionBook1" class="clonedBook"> 
      <label for="txtSkillName1"> 
       <abbr title="Required"> 
        <em><font color="red">*</font></em> 
       </abbr> 
       Skill Name 
      </label> 
       <input type="text" id="txtSkillName1" name="txtSkillName1" class="validate[required] inputLong" 
       runat="server" /> 

       <p class="power"> 
       <label for="txtSkillLevel"> 
        <abbr title="Required"> 
         <em><font color="red">*</font></em> 
        </abbr> 
        Skill Level</label> 
       <span> 
        <input type="text" id="txtSkillLevel1" name="txtSkillLevel1" class="validate[required] inputLong" 
         value="" /> 
       </span> 
      </p> 
      <p> 
       <label for="txtSkillDescription"> 
        <abbr title="Required"> 
         <em><font color="red">*</font></em> 
        </abbr> 
        Skill Description</label> 
       <span> 
        <textarea style="overflow: auto; resize: none" rows="3" cols="50" id="txtSkillDescription1" 
         name="txtSkillDescription1" class="validate[required] inputLong"></textarea> 
       </span> 
      </p> 

      </div> 
      <input type="button" id="btnAdd1" value="Add" /> 
       <input type="button" id="btnDel1" value="Remove" /> 
     </div> 
     <input type="submit" id="btnSave" class="styledButton" value="Save" /> 

вот мой JQuery

<script type="text/javascript"> 

    $(document).ready(function() { 

     $('#btnAdd1').click(function() { 

      var num = $('.clonedBook').length; // how many "duplicatable" input fields we currently have 
      var newNum = new Number(num + 1);  // the numeric ID of the new input field being added 

      // create the new element via clone(), and manipulate it's ID using newNum value 
      var newElem = $('#optionBook' + num).clone().attr('id', 'optionBook' + newNum); 


      // manipulate the name/id values of the input inside the new element 
      newElem.children(':nth-child(10n-8)').attr('id', 'txtSkillName' + newNum).attr('txtSkillName', 'txtSkillName' + newNum); 


      newElem.children(':nth-child(10n-4):nth-child(10n-8):first').attr('id', 'txtSkillDescription' + newNum).attr('txtSkillDescription', 'txtSkillDescription' + newNum); 

      // insert the new element after the last "duplicatable" input field 
      $('#optionBook' + num).after(newElem); 
      //   $('#apn-book' + num).after(newElem); 

      // enable the "remove" button 
      $('#btnDel1').attr('disabled', ''); 

      // business rule: you can only add 5 names 
      if (newNum == 5) 
       $('#btnAdd1').attr('disabled', 'disabled'); 


     }); 



     }) 
     $('#btnDel1').click(function() { 
      var num = $('.clonedBook').length; // how many "duplicatable" input fields we currently have 
      $('#optionBook' + num).remove();  // remove the last element 

      // enable the "add" button 
      $('#btnAdd1').attr('disabled', ''); 

      // if only one element remains, disable the "remove" button 
      if (num - 1 == 1) 
       $('#btnDel1').attr('disabled', 'disabled'); 
     }); 

    }); 


</script> 

То, что я пытаюсь сделать здесь когда Add кнопка - это щелчок по клону div, вместе с его элементами, а текстовые поля внутри div будут разными идентификаторами на основе клона, например (txtSkillName1, txtSkillName2 и так далее). Текстовое поле txtSkillName работает, но у меня есть проблема с txtSkillLevel1 и tx tSkillDescription1.

+0

Вместо того, чтобы использовать .children, попробуйте .find, который пересекает все дерево родителя (дети, детские дети и т. Д.) Вместо одного уровня? – garethb

+0

@garethb я пытался использовать .find, но он просто меняет только идентификатор главного div, а не клонированные ... –

+0

Это может помочь http://stackoverflow.com/a/10127093/853295 – garethb

ответ

1

См. Эту демонстрационную версию. Я думаю, что он делает то, что вы пытаетесь выполнить. Однако вам придется изменить код, чтобы он соответствовал вашим потребностям, я сделал только один клон.

http://jsfiddle.net/vj9RD/4/

$('#btnAdd1').click(function() { 

    // create the new element via clone(), and manipulate it's ID using newNum value 
    var newElem = $('#optionBook1').clone().attr('id', 'optionBook2'); 


    // manipulate the name/id values of the input inside the new element 
    $(newElem).find('[id=txtSkillName1]').attr('name', 'txtSkillName2');  
    $(newElem).find('[id=txtSkillName1]').attr('id', 'txtSkillName2'); 

    $(newElem).find('[id=txtSkillLevel1]').attr('name', 'txtSkillLevel2');  
    $(newElem).find('[id=txtSkillLevel1]').attr('id', 'txtSkillLevel2'); 

    $(newElem).find('[id=txtSkillDescription1]').attr('name', 'txtSkillDescription2');  
    $(newElem).find('[id=txtSkillDescription1]').attr('id', 'txtSkillDescription2'); 

    // insert the new element after the last "duplicatable" input field 
    $(newElem).insertAfter('#optionBook1'); 


}); 

Убедитесь, что изменить имя атрибута первым!

+0

спасибо за этого одного брата, я просто не могу его протестировать сейчас из-за того, что наш сервер в настоящее время работает на этот момент ... но будьте уверены, что я буду голосовать за этот ответ, когда я уже пробовал это в своем проекте .. спасибо –

+0

np, если он не работает так, как вы ожидаете, потому что я что-то неправильно понял, дайте мне знать. И не забудьте также изменить атрибут для меток. – garethb

+0

это сработало .. Большое вам спасибо за это –

Смежные вопросы