gpt4 book ai didi

javascript - 尝试缩小针对不同 ID 多次使用的点击事件?

转载 作者:行者123 更新时间:2023-11-28 16:26:18 25 4
gpt4 key购买 nike

我试图减少一些代码,基本上以下点击事件使用了 10 次,id 范围从 #topNavA - #topNavJ,事件中只有 2 部分发生了变化。谁能建议我如何为每次点击回收此代码?我已经添加了将从单击事件更改为单击事件的行的注释,但其余部分保持不变?欢迎所有建议。

$('#topNavA').click(function() {
$footerPush.hide();
$allMultipleElements.hide();

$('#section, #placement, .mobileControls').show(); // This line will change with different selectors
$('.mobileControls h1').replaceWith('<h1>Mobilizing Mobile, AL</h1>'); // This line will change with a different header 1
$('.mobileControls h2').replaceWith('<h2>Overview</h2>'); // This line will change with a different header 2
$('.menuTitle').removeClass('active');
$('.lightbox').remove();

$('#nav li > a').removeClass('active');
$('#nav li span a').css({
'color': '#8F8F8F'
});

$('#topNav').addClass('active');
$(this).css({
'color': '#e8af20'
});
});

谢谢凯尔

最佳答案

一种选择是使用数据。您可以在存储变量数据的元素上拥有 3 个 data- 属性。像这样的事情:

<a href="..." id="topNavA" class="topNavLink" data-selector="#section, #placement, .mobileControls">something</a>
<小时/>
$(".topNavLink").click(function(){
var selector = $(this).data("selector");

$(selector).dosomething();
});

该技术的示例:http://jsfiddle.net/mPQfJ/1/

关于javascript - 尝试缩小针对不同 ID 多次使用的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7895854/

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