[英]How can I apply a jQuery function to all elements with the same class.?
JQuery return value for all same name class = 2.53
(first element value applied for all Span) 所有相同名称类的jQuery返回值=
2.53
(适用于所有Span的第一个元素值)
How do I get different values? 如何获得不同的价值?
(Edit:) HTML code: (编辑:)HTML代码:
<div class='ratingInfo'>
<table class='rating_table' border='0' cellpadding='0' cellspacing='0'>
<tbody>
<tr>
<td>
<div class='review-rating'>10</div>
</td>
<td>
<div class='stars1'></div>
</td>
</tr>
</tbody>
</table>
</div>
<div class='ratingInfo'>
<table class='rating_table' border='0' cellpadding='0' cellspacing='0'>
<tbody>
<tr>
<td>
<div class='review-rating'>1</div>
</td>
<td>
<div class='stars1'></div>
</td>
</tr>
</tbody>
</table>
</div>
JavaScript JavaScript的
$( document ).ready(function() {
$( ".stars1" ).html("<span class='stars'>"+$('.review-rating').text()+"</span>");
$('span.stars').stars();
});
$.fn.stars = function() {
return $(this).each(function() {
$(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
});
}
Because $('.review-rating').text()
is grabbing the first element every time, it does not know you want the one that is beside the element. 因为
$('.review-rating').text()
每次都在抓取第一个元素,所以它不知道您想要元素旁边的那个。 You need to code it to look there. 您需要对其进行编码才能在此处查看。
$( ".stars1" ).each( function () {
var star = $(this);
star.html("<span class='stars'>" + star.prev('.review-rating').text() + "</span>");
});
with the new HTML code, the above will not work since the elements are NOT siblings. 使用新的HTML代码,由于元素不是兄弟姐妹,因此上述操作将无效。 That is why it is important to have the actual code!
这就是为什么拥有实际代码很重要的原因! You need to look for a common parent and find the element within it, in this case you have the TR that contains both.
您需要寻找一个公共的父对象,并在其中找到元素,在这种情况下,您需要包含两个元素的TR。 So to get the parent, use closest()
因此,要获取父项,请使用closest()
$( ".stars1" ).each( function () {
var star = $(this);
var rating = star.closest("tr").find(".review-rating").text();
star.html("<span class='stars'>" + rating + "</span>");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.