首页 > 解决方案 > 带有jquery的循环函数类名

问题描述

我必须遵循代码:

$( ".content.one" ).clone().appendTo( ".cat.one .details" );
$( ".content.two" ).clone().appendTo( ".cat.two .details" );
$( ".content.three" ).clone().appendTo( ".cat.three .details" );

我想像这样循环

var obj = {
one: 'one',
two: 'two',
three: 'three'
};
$.each(obj, function (index, value) {
  $( ".content.(value)" ).clone().appendTo( ".cat.(value) .details" );
});

但我不知道如何在类中使用“值”

标签: jqueryeach

解决方案


使用模板文字

var obj = {one: 'one',two: 'two',three: 'three'};

$.each( obj, function( key, value ) {
  $(`.content.${value}`).clone().appendTo(`.cat.${value} .details`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="content one">One</div>
<div class="content two">Two</div>
<div class="content three">Three</div>

<br/>
<div class="cat one"><div class="details"></div></div>
<div class="cat two"><div class="details"></div></div>
<div class="cat three"><div class="details"></div></div>

注意obj是一个对象,根据jQuery.each,回调将作为参数传递keyvalue而不是indexand value


推荐阅读