Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据另一个div的内容更改类的名称_Javascript_Jquery - Fatal编程技术网

Javascript 根据另一个div的内容更改类的名称

Javascript 根据另一个div的内容更改类的名称,javascript,jquery,Javascript,Jquery,假设这种结构: <div class="item price-class"> <div class="product-box"> <h2 class="price">340</h2> </div> </div> <div class="item price-class"> <div class="product-box"> <h2 class="price">450&

假设这种结构:

<div class="item price-class">
  <div class="product-box">
  <h2 class="price">340</h2>
  </div>
</div>

<div class="item price-class">
  <div class="product-box">
  <h2 class="price">450</h2>
  </div>
</div>

<div class="item price-class">
  <div class="product-box">
  <h2 class="price">870</h2>
  </div>
</div>

340
450
870
如何将名称.price类更改为.340 price、.450 price、.870 price(并能够将其应用于多个项目动态?

可能是:

$('.price-class').each(function(){
    var $this = $(this);
    $this
        .removeClass('price-class')
        .addClass($this.find('.price').text() + '-price');
});
文件:

检查此项

$('.price').each(function(){

    $(this).parents('.price-class').removeClass('price-class').addClass($(this).html()+'-price');
});
您需要使用jQuery使用

$("div.item").each(function() {
    var element = $(this).find(".price");
    var price = element.text();
    element.removeClass("price");
    element.addClass(price + "-price");
});
使用jQuery

$(document).ready(function(){

    $(".price-class").each(function(){
        price = $(this).text();
        $(this).removeClass("price-class").addClass(price+"-class");
    })

});
看看这把小提琴:


创建.340.450和.870类,并在需要时附加它们?这是一个很好的解决方案,但正如我所说的,我需要动态地执行此操作。将有许多具有许多不同价格的项目,每个项目的价格都应作为类名添加到主项目容器中。请发布您当前正在尝试使用so w执行此操作的帖子e可以看看为什么它不起作用。此外,添加一个(或类似的)来演示这个问题也有帮助。为什么要这样做?创建这些新类的目的是什么?
$(".item .product-box .price").each(function(ind, el) {
    var txt = $(el).text();
    $(el).closest(".item").addClass(txt + "-price");
});