2011-08-14 2 views
0

모바일 html 앱용 코드 세그먼트를 많이 반복하고 있습니다. 다운로드 시간을 단축하기 위해 html 코드를 줄이고 jQuery로 자동화하려고 노력해 왔지만 jquery는 매우 장황합니다. 다음은 예제입니다. 이런 유형의 일을 간략하고 효율적으로 만들 수 있습니까?jquery DOM 조작 -이 작업을보다 효율적으로 수행

<!DOCTYPE html> 
<html> 
<head> 

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" /> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> 
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script> 
<script type="text/javascript"> 

tplCnf = "\n\n\ 
     <center>\n\ 
     <div data-role='content' data-theme='b'>\n\ 
       <fieldset data-role='controlgroup' data-type='horizontal'>\n\ 
        <input type='radio' name='FMT' id='' value='S' checked='checked' /><label name='FMT' for=''>Serial</label>\n\ 
        <input type='radio' name='FMT' id='' value='P' /><label      name='FMT' for=''>Parallel</label>\n\ 
        <input type='radio' name='FMT' id='' value='O' /><label      name='FMT' for=''>Other</label>\n\ 
       </fieldset>\n\ 
     </div>\n\ 
     </center>"; 

$(document).ready(function() 
{ 
    /* This is used to populate configuration types */   
    var groups = ['A','B','C','D','E','F']; 

    /* add data config type types */ 
     for (var myLetters in groups){ 
      // clone fragment of html 
      myTmpl = $(tplCnf); 

      // create a unique name for Configuratin radio boxes and corresponding labels 
      myTmpl.find('input[name="FMT"]')     
       .attr("name", "FMT-"+groups[myLetters]);     
      myTmpl.find('label[name="FMT"]')     
       .attr("name", "FMT-"+groups[myLetters]); 

      // apply id name to first configuration radio box 
      name1 = "preConfigRadio-" + groups[myLetters] + "1";    
      myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(0)') 
       .attr("id", name1) 
      myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(0)') 
       .attr("for", name1); 

      // apply id name to second configuration radio box 
      name2 = "preConfigRadio-" + groups[myLetters] + "2";    
      myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(1)') 
       .attr("id", name2); 
      myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(1)') 
       .attr("for", name2); 

      // apply id name to third configuration radio box 
      name3 = "preConfigRadio-" + groups[myLetters] + "3"; 
      myTmpl.find('input[name="FMT-"+ groups[myLetters]]:eq(2)') 
       .attr("id", name3); 
      myTmpl.find('label[name="FMT-"+ groups[myLetters]]:eq(2)') 
       .attr("for", name3); 

      // then append 
      myTmpl.appendTo("#placeholder"+groups[myLetters]).trigger('create');          
     } 
}); 

</script> 

</head> 
<body> 

<!-- *** Navigation bar *** --> 
<div data-role="page" id="preHelpTab"> 
<div data-role="header" data-position="inline"> 

<input type="hidden" id="preBeginRequestDtls" name="BeginRequestDtls" value="" /> 

     <div id='groupA' class='preGroups'> 
     This is Group A 
      <div id='placeholderA' ></div> 

     </div> 

     <div id='groupB' class='preGroups'> 
     This is Group B 
      <div id='placeholderB' ></div> 
     </div> 

     <div id='groupC' class='preGroups'> 
     This is Group C 
      <div id='placeholderC' ></div> 
     </div> 

     <div id='groupD' class='preGroups'> 
     This is Group D 
      <div id='placeholderD' ></div> 
     </div> 

     <div id='groupE' class='preGroups'> 
     This is Group E 
      <div id='placeholderE' ></div> 
     </div> 

     <div id='groupF' class='preGroups'> 
     This is Group F 
      <div id='placeholderF' ></div> 
     </div> 
</div> 
</div> 
+0

일부 인용 부호가 누락 된 것처럼 보입니다 .find ('input [name = "FMT -"+ 그룹 [myLetters] : eq (0)])가 의도 한대로 작동하고 있습니다. – Sinetheta

+0

재시험. 그것은 당신을 위해 실패합니까? – bob

답변

0

논리는 좋지만 코드를 여러 번 찾지 않고 로컬 변수를 캐싱하여 코드의 성능을 즉석에서 예측할 수 있습니다.

<script id="inputTemplate" type="text/html"> 
    <input type='radio' name="${groupName}" id="${id}" value="${value}" /> 
    <label name="${labelName}" for="${for}">${labelValue}</label> 
</script> 

그런 다음이 같은 입력 그룹에 대한 템플릿을 만들 수 있습니다 : jQuery Templates

이 같은 하나의 입력 요소 템플릿 만들기 사용을 고려이

$(document).ready(function() 
{ 
    /* This is used to populate configuration types */   
    var groups = ['A','B','C','D','E','F'], inputs, label, name; 

    /* add data config type types */ 
     for (var myLetters in groups){ 
      // clone fragment of html 
      myTmpl = $(tplCnf); 

      // create a unique name for Configuratin radio boxes and corresponding labels 
      inputs = myTmpl.find('input[name="FMT"]')     
       .attr("name", "FMT-"+groups[myLetters]);     
      lables = myTmpl.find('label[name="FMT"]')     
       .attr("name", "FMT-"+groups[myLetters]); 

      for(var i =0;i<3;i++){ 
       name = "preConfigRadio-" + groups[myLetters] + (i+1);    
       inputs.eq(i).attr("id", name) 
       labels.eq(i).attr("for", name); 
      } 

      // then append 
      myTmpl.appendTo("#placeholder"+groups[myLetters]).trigger('create');          
     } 
}); 
0

를 살펴 보자

<script id="groupTemplate" type="text/html"> 
    <center> 
     <div data-role='content' data-theme='b'> 
      <fieldset data-role='controlgroup' data-type='horizontal'> 
       ${inputItem} 
      </fieldset> 
     </div> 
    </center> 
</script> 

이제 두 가지를 모두 사용하면 실제 jQuery 코드가 더 많이 관리 할 수있는!

은 입력에 대한 귀하의 데이터 집합을 정의합니다 마지막으로

var inputDataSet = [ 
    { groupName: "FMT-A", id: 1, value: "", labelName: "1A", for: "", labelValue: "123" }, 
    { groupName: "FMT-A", id: 2, value: "", labelName: "2A", for: "", labelValue: "123123" }, 
    { groupName: "FMT-A", id: 3, value: "", labelName: "3A", for: "", labelValue: "1231231" } 
] 

하나 개의 라인을 캐스팅하고 추가 할 :

$("#groupTemplate").tmpl($("#inputTemplate").tmpl(inputDataSet)).appendTo("#placeholder"); 

난 당신이 완벽하게 일치하지 않는 한 실제 값과 논리를 알고 있지만 본질적이다 어떻게 이런 종류의 일을해야합니까. jQuery 템플릿을 사용하면 가변 데이터 기반 HTML 요소를 페이지에 삽입하려는 경우 코드 관리 효율성을 높이고 DOM 조작을보다 명확하게 처리 할 수 ​​있습니다.

또한 POST 결과 데이터를 손쉽게 표시 할 수 있으므로 AJAX 호출과 함께 광범위하게 사용됩니다.

+0

좋은 아이디어지만, 모바일 앱인 경우 가능한 경우 추가 코드를 추가하지 않는 것이 좋습니다. – bob

+0

충분히 축소 된 파일이 오늘날 대부분의 모바일 브라우저에서 캐시되는 4.8KB이기 때문에 여전히 고려해야 할 가치가 있습니다. 나는 당신이 여러 페이지에서 이것을 필요로하는 것으로 추정하고 있는데,이 경우 반드시가는 길이다. –