Jquery长度不使用名称中包含变量的元素

时间:2016-06-17 04:46:03

标签: jquery variables

如果您只放置$('li').lenght;

,则有效 如果向名称$('#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>

2 个答案:

答案 0 :(得分:1)

Id不能在html中重复,Id对于页面中的每个元素都应该是唯一的,但您可以在此处使用class而不是Id。

&#13;
&#13;
$(document).ready(function(){
   $("button").click(function(){
      var tu = '1';
      alert($(".uno_"+tu).length);
   });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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>