[英]JQuery loop through each div id
i am trying to use jquery to loop through each div tag with id = "rate". 我正在尝试使用jquery遍历id =“ rate”的每个div标签。 jquery would then preform function on the seperate divs.
然后,jQuery将在单独的div上执行功能。 here's my code:
这是我的代码:
info.html
info.html
<html>
<input class="rate" type="hidden" value="<?php echo $rate;?>" /></p>
<div class='rating_bar'>
<!-- div element that contains full stars with percentage width,
which represents rating -->
<div class="rating" style='width:40%;'>
</div>
</div>
</html>
rate.js
rate.js
$(document).ready(function() {
$('.rate').each(function( index ){
var value = this.value;
if(value >= 0 && value <= 5)
{
value = Math.round((value/5)*100);
$('.rating').each(function(){
$(this).width(value + '%');
}
}}
else
{
alert("Incorrect value, rating must be between 0 and 5");
}
});
});
style.css
style.css
.rating_bar {
width: 150px;
height: 40px;
background: url(../images/rate-btn2.png);
background-repeat: repeat-x;
background-position: 0 0;
text-align: left;
}
.rating {
height: 40px;
background: url(../images/rate-btn2-hover.png);
background-position: 0 -1px;
background-repeat: repeat-x;
}
Question:
题:
what i have are multiple hidden textboxes with div id="rate". 我所拥有的是带有div id =“ rate”的多个隐藏文本框。 jquery only affects first div id.how do loop through each div id?
jQuery只影响第一个div ID。如何遍历每个div ID?
First of all ID
s SHOULD be unique in programming world. 首先,
ID
在编程世界中应该是唯一的。 Anyways you should change your markup to use class instead of ID. 无论如何,您应该将标记更改为使用类而不是ID。 See:
看到:
<div class="rate">800</div>
Then you can use jquery to get the text inside that div: 然后,您可以使用jquery获取该div中的文本:
$('.rate').each(function(){
var textValue = this.text();
// anything you want to do here.
});
Note : this
refers to the current jquery object inside the loop. 注意 :
this
是指循环内的当前jquery对象。
Replace : 更换:
$('.rate').each(function( index ){
var value = document.getElementById("rate").value;
// ...
});
with : 与:
$('.rate').each(function( index ){
var value = this.value;
// ...
});
to get the value of the input
element you are iterating over. 获取要迭代的
input
元素的值。
Edit. 编辑。 Based on your comments, you need to link the n-th
div.rating
with the value of the n-th input.rate
. 根据您的意见,您需要在第n个链接
div.rating
与第n的值input.rate
。 For that we can use the .eq
function of jQuery, to get the n-th child of an array of elements. 为此,我们可以使用jQuery的
.eq
函数来获取元素数组的第n个子元素。 See code below : 参见下面的代码:
$(document).ready(function () {
$('.rate').each(function (index) {
var value = this.value;
if (value >= 0 && value <= 5) {
value = Math.round((value / 5) * 100);
$('.rating').eq(index).width(value + '%');
// ^^^
// We get the corresponding .rating element
} else {
alert("Incorrect value, rating must be between 0 and 5");
}
});
});
And here is a working fiddle 这是一个工作的小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.