【问题标题】:Jquery: Select class and insert ".attr(***)" into all of that same classJquery:选择类并将“.attr(***)”插入到所有同一个类中
【发布时间】:2011-11-02 13:36:18
【问题描述】:
var str = $('.rating').html();
$.trim(str);
$('.rating').prepend.attr('class', 'rating-' + str.replace(/\s/g, ""));

<div class="rating">1</div>
<div class="rating">2</div>
<div class="rating">3</div>

Change to this:
<div class="rating-1">1</div>
<div class="rating-2">2</div>
<div class="rating-3">3</div>

.prepend 如何与 .attr 一起使用?似乎我找不到关于 append 和 attr 的任何信息。

我要做的就是选择一个类并将它们替换为 1 类、2 类、3 类等。

【问题讨论】:

  • 您还需要包含您的 HTML。
  • prepend 不能那样工作......

标签: jquery insert append attr


【解决方案1】:

这是你想要的吗?

因为你改变了属性

attr('class'

我认为你应该使用 removeClass 和 addClass

var cnt = 1; 
$('.rating').each(function(){
    $(this).removeClass("rating");
    $(this).addClass("rating-" + cnt);
    cnt = ctn + 1;

});

我认为它会做到这一点,因此每个班级评级将被评级-n 替换,其中每次更改班级时 n 将增加 1

【讨论】:

  • 啊当然,这将循环通过所有。谢谢大佬现在就试试。
【解决方案2】:

prepend 和 append 作用于 DOM 元素,而不是字符串。使用 removeClass 和 addClass 来完成你想要做的事情:

$('.rating').removeClass("rating").addClass(function () {
    return "rating-" + $(this).html();
});

【讨论】:

    【解决方案3】:

    .prepend() 方法将指定的内容作为 jQuery 集合中每个元素的第一个子元素插入(要将其作为最后一个子元素插入,请使用 .append())。

    Documentation

    如果你只想替换一个类,使用 $(element).addClass 和 $(element).removeClass,而不是 prepend。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 2014-09-09
      • 2015-10-04
      • 1970-01-01
      相关资源
      最近更新 更多