如果您只放置$('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>
答案 0 :(得分:1)
Id不能在html中重复,Id对于页面中的每个元素都应该是唯一的,但您可以在此处使用class而不是Id。
$(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;
答案 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>