谁能协助我简化这个jQuery的工作?我听说forEach可以在那帮我,但不知道如何使用它。

<script>
jQuery(document).ready(function($){

$("div#accordion .panel:nth-child(1)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/WLDMCHPLAY-QF-FANS1-e1469784860667.jpg) !important;");
});

$("div#accordion .panel:nth-child(2)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/mountains-snow-cars-bentley-roads-vehicles-bentley-continental-bentley-continental-gt-front-angle-vi-2015.jpg) !important;");
});

$("div#accordion .panel:nth-child(3)").click(function(){
$(".changer .vc_column-inner").css("cssText", "background-image: url(wp-content/uploads/2016/04/1007.jpg) !important;");
});

}(jQuery));
</script>

最佳答案

您可以使用数组简化它。将CSS属性值存储在数组中,并根据元素索引更新值(可以使用index()方法获取索引)。

jQuery(document).ready(function($) {
  // store URLs in an array for selecting based on the index
  var css = [
    "url(wp-content/uploads/2016/04/WLDMCHPLAY-QF-FANS1-e1469784860667.jpg) !important;",
    "url(wp-content/uploads/2016/04/mountains-snow-cars-bentley-roads-vehicles-bentley-continental-bentley-continental-gt-front-angle-vi-2015.jpg) !important;",
    "url(wp-content/uploads/2016/04/1007.jpg) !important;"
  ],
    // store the reference to the element for future reference
  $ele = $("div#accordion .panel").click(function() {
    // get the css value based the index of clicked element
    // with help of referenced variable , here index means the position within the referenced selector
    // where `this` refer to the clicked element
    $(".changer .vc_column-inner").css("cssText", "background-image:" + css[$ele.index(this)]);
  });
}(jQuery));

10-06 07:45
查看更多