如何将jQuery函数应用于具有相同类的所有元素? [英] How can I apply a jQuery function to all elements with the same class.?

查看:72
本文介绍了如何将jQuery函数应用于具有相同类的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有同名类的jQuery返回值= 2.53(适用于所有Span的第一个元素值)

JQuery return value for all same name class = 2.53 (first element value applied for all Span)

如何获得不同的值?

() 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));
    });
 }

推荐答案

因为$('.review-rating').text()每次都在抓取第一个元素,所以不知道您想要元素旁边的那个元素.您需要对其进行编码才能在此处查看.

Because $('.review-rating').text() is grabbing the first element every time, it does not know you want the one that is beside the element. 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>");
});

使用新的HTML代码,由于元素不是兄弟姐妹,因此上述操作将无效.这就是为什么拥有实际代码很重要的原因!您需要寻找一个公共的父对象,并在其中找到元素,在这种情况下,您需要包含两个元素的TR.因此,要获取父项,请使用closest()

with the new HTML code, the above will not work since the elements are NOT siblings. 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. So to get the parent, use closest()

$( ".stars1" ).each( function () {
    var star = $(this);
    var rating = star.closest("tr").find(".review-rating").text();
    star.html("<span class='stars'>" + rating + "</span>");
});

这篇关于如何将jQuery函数应用于具有相同类的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆