gpt4 book ai didi

javascript - 如何用变量简化jquery代码?

转载 作者:行者123 更新时间:2023-11-28 19:29:48 25 4
gpt4 key购买 nike

我有这个 jQuery 代码,用于通过图像预览切换 float 部分。图层始终相同,只是图像发生变化。我设法简化了 css 中的代码,为元素提供了类。一切正常。然而我发现优化 jQuery 代码非常困难。我对 jQuery 和 Javascript 还很陌生,所以我不太确定如何做到这一点。该代码工作正常,但它非常巨大,我想简化它。我相信我必须使用变量。但如何呢?任何帮助将不胜感激:)

这是我的 jQuery 代码:

//first layer

$(document).ready(function() {
$('.toggleLayer').click(function(){
$('#FloatingLayer').fadeIn('fast');
});
});

$(document).ready(function() {
$('#FloatingLayer').click(function(){
$(this).fadeOut('fast');
});
});


//second layer

$(document).ready(function() {
$('.toggleLayer2').click(function(){
$('#FloatingLayer2').fadeIn('fast');
});
});

$(document).ready(function() {
$('#FloatingLayer2').click(function(){
$(this).fadeOut('fast');
});
});



// third layer

$(document).ready(function() {
$('.toggleLayer3').click(function(){
$('#FloatingLayer3').fadeIn('fast');
});
});

$(document).ready(function() {
$('#FloatingLayer3').click(function(){
$(this).fadeOut('fast');
});
});

这是我的 html:

<div class="fourcol toggleLayer">   
<img src="img1" class="center" width="100%">
</div>

<div class="fourcol toggleLayer2">
<img src="img2.jpg" class="center" width="100%">
</div>

<div class="fourcol toggleLayer3">
<img src="img3" class="center" width="100%" >
</div>

float 部分:

<section class="Floating" id="FloatingLayer">
<img src="img1.jpg" class="floatimg"/>
</section>

<section class="Floating" id="FloatingLayer2">
<img src="img2.jpg" class="floatimg"/>
</section>

<section class="Floating" id="FloatingLayer3">
<img src="img3.jpg" class="floatimg"/>
</section>

最佳答案

根本不改变你的标记...

var $body = $(document.body);

$body.on('click', '[class~=toggleLayer]', function () {
var layerNum = this.className.match(/toggleLayer(\d+)/)[1];

$('#FloatingLayer' + layerNum).fadeIn('fast');
});

$body.on('click', '.Floating', function () {
$(this).fadeOut('fast');
});

但是,这里的行为并不明确,最好修改您的标记并使用自定义 data- 属性,如 Pointy 建议的那样。

关于javascript - 如何用变量简化jquery代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27090463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com