2012-11-27 4 views
0

이것은 코드 미화 질문의 더하지만 ...최적화 jQuery 코드 - 반복 부품 여전히

나는이 HTML을 가지고 : (단축) 나는 변경 복사 할

<div id="sablona" style="display:none;"> 
    <div style="position:relative;"> 
     <fieldset> 
      <img class="sm_kont" src="../../include/img/remove_16.png" title="Smazat kontakt" alt="Smazat kontakt" /> 
      <legend></legend> 
      <table> 
       <tr> 
        <td> 
         <label for="jmeno_n">jméno</label> 
         <input name="jmeno_n" id="jmeno_n" type="text" value="" /> 
        </td> 
        <td> 
         <label for="pohlavi_n">pohlaví</label> 
         <select name="pohlavi_n" id="pohlavi_n"> 
          <option value="0"></option> 
          <option value="m">muž</option> 
          <option value="z">žena</option> 
         </select> 
        </td> 
       </tr> 
       <tr> 
        <td colspan="4"> 
         <label for="adresa_n">adresa</label> 
         <textarea name="adresa_n" id="zpr_adresa_n" rows="3"></textarea> 
        </td> 
       </tr> 
      </table> 
     </fieldset> 
    </div> 
</div> 

몇 가지 중요한 속성. 다음 코드는 제가 사용된다

var count = 0; 

function pridat_kontakt() { 
    var novy_kontakt = $("#novy_kontakt").val(); 
    if (novy_kontakt.length == 0) alert("Typ kontaktu nemůže být prázdný!"); 
    else { 
     var kopie = $("#sablona").children().clone(true); 
     kopie.find("legend").text(novy_kontakt); 
     kopie.find("label, input, select, textarea").each(function() { 
      if (typeof $(this).attr("name") != 'undefined') { 
       if ($(this).attr("name").length > 0) { 
        var new = $(this).attr("name") + count; 
        $(this).attr("name", new); 
       } 
      } 
      if (typeof $(this).attr("for") != 'undefined') { 
       if ($(this).attr("for").length > 0) { 
        var new = $(this).attr("for") + count; 
        $(this).attr("for", new); 
       } 
      } 
      if (typeof $(this).attr("id") != 'undefined') { 
       if ($(this).attr("id").length > 0) { 
        var new = $(this).attr("id") + count; 
        $(this).attr("id", new); 
       } 
      } 
     }); 
     $("[name='fedit']").append(kopie); 
     $("#novy_kontakt").val(""); 
     count++; 
    } 
} 

모든 것이 잘 작동, 그것은 너무 좋아 보이지 않습니다. 누군가 그것을 아름답게하는 방법을 생각할 수 있습니까? .each() 부분을 의미합니다.

+2

'new'은 키워드이며, 변수 이름으로 사용해서는 안된다. – zzzzBov

답변

2

당신은 함수를 선언하고 각 부분에서 그것을 사용할 수 있습니다

var checkAttr = function(jelem, attrName) { 
    var attrValue = jelem.attr(attrName); 
    if (typeof attrValue != 'undefined' && attrValue.length > 0) { 
     var newAttr = attrValue + count; 
     jelem.attr(attrName, newAttr); 
    } 
} 
kopie.find("label, input, select, textarea").each(function() { 
     var jthis = $(this); 
     checkAttr(jthis, "name"); 
     checkAttr(jthis, "for"); 
     checkAttr(jthis, "id"); 
});