2016-06-17 1 views
0
당신이 이름에 변수를 추가하면 $('li').lenght;

JQuery와 길이는 이름으로 변수 요소와 작동하지

길이가 작동하지 않는 경우에만 넣을 경우 작동

$('#id_'+variable).length;

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
     <script> 
      $(document).ready(function() { 
       $("button").click(function() { 
        var tu = '1'; 
        alert($("#uno_" + tu).length); 
        // IT WORKS IF YOU PUT ONLY $('li').lenght; 
       }); 
      }); 
     </script> 
    </head> 

    <body> 
     <button>Alert the number of li elements</button> 
     <ul> 
      <li id="uno_1">Coffee</li> 
      <li id="uno_1">Milk</li> 
      <li id="uno_1">Soda</li> 
     </ul> 
    </body> 

</html> 
+0

** ID는 항상'클래스 = 'uno_1'' 다음 JQuery와의'$ 같은 **'사용 클래스 instead' 고유해야합니다 (". UNO _"+ TU) .length' – guradio

+0

https://jsfiddle.net/kks320w0/ 작동합니다. js의 순서를 확인하십시오 – Sherlock

+0

감사합니다! –

답변

0
이드에 복제 할 수 없습니다

html, Id는 페이지의 각 요소에 대해 고유해야하지만 ID 대신 여기에서 클래스를 사용할 수 있습니다.

$(document).ready(function(){ 
 
    $("button").click(function(){ 
 
     var tu = '1'; 
 
     alert($(".uno_"+tu).length); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<button>Alert the number of li elements</button> 
 

 
<ul> 
 
    <li class="uno_1">Coffee</li> 
 
    <li class="uno_1">Milk</li> 
 
    <li class="uno_1">Soda</li> 
 
</ul>

0
<html> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
    <script> 
     $(document).ready(function(){ 
      $("button").click(function(){ 
    var tu = 1; 
       alert($("#uno_"+tu).html().length); 

      }); 
     }); 
    </script> 
    </head> 
    <body> 

    <button>Alert the number of li elements</button> 

    <ul> 
     <li id="uno_1">phpsiliguri.com</li> 
     <li id="uno_2">google.com</li> 
     <li id="uno_3">yahoo.com</li> 
    </ul> 
    </body> 
</html>