如何将其简化为一个函数:
$("#tab-one").click(function() {
var imageUrl = "img/img-1.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
$("#tab-two").click(function() {
var imageUrl = "img/img-2.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
$("#tab-three").click(function() {
var imageUrl = "img/img-3.png";
$(".masthead.product-detail").css("background-image", "url(" + imageUrl + ")");
});
提前非常感谢!
创建一个以选项卡 ID 作为键、以相应的图像 URL 作为值的对象数组。
为所有选项卡提供通用类
现在您可以使用单击处理程序来减少代码,如下所示:
$(".tab").click(function() {
$(".masthead.product-detail").css("background-image", "url(" + ImgUrls[$(this).attr('id')] + ")");
});
工作片段:
var ImgUrls = {
'tab-one': 'img/img-1.png',
'tab-two': 'img/img-2.png',
'tab-three': 'img/img-3.png'
};
$(".tab").click(function() {
$(".masthead.product-detail").css("background-image", "url(" + ImgUrls[$(this).attr('id')] + ")");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="masthead product-detail">Hey text</div>
<br>
<div>
<div class="tab" id="tab-one">Click tab-one</div>
<div class="tab" id="tab-two">Click tab-two</div>
<div class="tab" id="tab-three">Click tab-three</div>
</div>