2012-03-14 1 views
1

동시에 여러 div ("show"+ i)에 함수를 할당하려고합니다. 각 호출은 다른 div ("theDiv" + i), "+ i"는 작동하지 않습니다.

$("#show"+i).click(function() 
{ 
$("#theDiv"+i).show("normal"); 
}); 

"i"의 값 (0,1,2 ...)을 다시 작성하면 코드가 작동합니다. 그런데 왜 이것을 고칠 수 있습니까? 이 전체 기능입니다 :

function getInfoProduits1() 
{ 

    var request = new XMLHttpRequest(); 
    if(i<idProduits.length) 
     { 
      request.open("GET","http://patisserie-orient.fr/prestashop/prestashop/api/products/"+idProduits[i]+"?PHP_AUTH_USER="+PHP_AUTH_USER+"&ws_key="+ws_key,true); 

      request.onreadystatechange = function() 
       { 
        if(request.readyState==4) 
        { 
         //alert("Status2 is "+request.status); 
         if (request.status == 200 || request.status == 0) 
         { 
          response1 = request.responseXML.documentElement; 
          nameProduits[i] = response1.getElementsByTagName('name')[0].getElementsByTagName('language')[0].firstChild.data; 
          //alert(nameProduits[i]); 
          priceProduits[i] = response1.getElementsByTagName('price')[0].firstChild.data+" €"; 
          //alert(priceProduits[i]); 
          descriptionProduits[i] = response1.getElementsByTagName('description_short')[0].getElementsByTagName('language')[0].firstChild.data; 
          //alert(descriptionProduits[i]); 
          quantitieProduitsDisponible[i] = response1.getElementsByTagName('quantity')[0].firstChild.data; 
          //alert(quantitieProduitsDisponible[i]); 

          maDiv = document.createElement("div"); 
          maDiv.id = 'id_de_la_div'+i; 

          malabel = document.createElement("div"); 
          malabel1 = document.createElement("div"); 
          mon_bouton1 = document.createElement("button"); 
          maDiv2 = document.createElement("div"); 
          mon_bouton1.id="show"+i; 
          maDiv2.id="theDiv"+i; 
          maDiv2.innerHTML="Détails:"; 
          maDiv2.style.display="none"; 
          //mon_bouton1.value='click'; 

          $("#show"+i).click(function(){ 

      $("#theDiv"+i).show("normal"); 
      }); 
         mon_bouton1.onclick='aff();'; 
          malabel.innerHTML=nameProduits[i]; 
          malabel1.innerHTML=priceProduits[i]; 
          maDiv.innerHTML='<img src="Images/Icones/dollars.png" width="50" height="50" align="right">'; 
          //maDiv.innerHTML='<button type="button" id="show" onclick="aff();">Détails</button> '; 
          maDiv.className="ui-bar ui-bar-e cadre"; 
          document.getElementById("divbar").appendChild(maDiv); 
          document.getElementById('id_de_la_div'+i).appendChild(malabel); 
          document.getElementById('id_de_la_div'+i).appendChild(malabel1); 
          document.getElementById('id_de_la_div'+i).appendChild(mon_bouton1); 
          document.getElementById('id_de_la_div'+i).appendChild(maDiv2); 
          maDivvide = document.createElement("div"); 
          maDivvide.innerHTML='<br>'; 
          document.getElementById("divbar").appendChild(maDivvide); 
          i++; 
          getInfoProduits1(); 
         } 
        } 
       } 

      request.send(); 

     } 
    else 
     { 
      return; 
     } 

} 
+3

어떻게 정의합니까? 관련 코드를 게시 할 수 있습니까? – j08691

+0

이 더 많은 기능을 보여 주므로 'i'의 초기화를 검증 할 수 있습니다. – Fourth

+0

초기화하고 'i'에 값을 할당하는 코드를 게시 할 수 있습니까? –

답변

3

난 당신이 정말 무슨 뜻인지 이해가 안하지만 어쩌면 이것은 당신이 당신이 고전적인 실수 중 하나 희생양이 한 생각

//attach an event handler to all elements with an id that starts with "show" 
$("[id^=show]").click(function(){ 
    //get only the number from the clicked id 
    var i = this.id.replace("show", ""); 
    //show the relevant div 
    $("#theDiv"+i).show("normal"); 
}); 
+0

+1, 깔끔한 속임수입니다 – JaredPar

+0

멋진 솔루션 !! 7amdoulellah !! 고맙다 @ 니콜라 펠 루체 티 –

0

을 필요로하는 무슨이다 , "죽음이 줄에 서있을 때 결코 시칠리아에 대항하지 마라."보다 약간 덜 유명하다.

폐쇄에서 사용되었지만 그 밖에서 정의 된 변수는 참조로 전달됩니다. 모든 사용자는 'i'를 공유합니다. 따라서 함수를 호출 할 때마다 'i'는 닫힌 값을 설정할 때 설정된 값이 아니라 마지막 값과 항상 동일하다는 것을 알 수 있습니다. 당신은 당신에게 당신의 종결을 제공하는 함수를 통해 'i'를 실행함으로써 이것을 고친다. 함수가 값으로 전달되기 때문에 'i'의 현재 값이 클로저에 바인딩됩니다.

function gimmeAFunctionToDoThatThingThatNeedsDoing(i) { 
    return function() { 
     // Move closure here 
    }; 
} 
관련 문제