gpt4 book ai didi

javascript - 消除 jQuery 脚本中的冗余代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:11 25 4
gpt4 key购买 nike

我已经设置了一个页面,使用 jQuery .load 函数通过 AJAX 加载数据。

通过单击选项卡栏上的链接加载每个新文件后,我使用 jQuery 将所选选项卡的颜色设置为黄色。我尝试使用 .toggleClass 函数将 li 元素的类设置为事件状态,这样它就会变成黄色,但没有骰子,所以我求助于重置每次 CSS。

如何去除冗余代码,或者大修脚本?

无论如何,这是 jQuery 脚本。欢迎任何帮助!

$(document).ready(function () {
$('a#catalog').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/catalog.html");
});
$('a#request').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/request.html");
});
$('a#publisher').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/publisher.html");
});
$('a#incoming').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/incoming.html");
});
$('a#finished').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/finished.html");
});
$('a#shipments').click(function() {
$("#nav ul li a").css("color","white");
$(this).css("color","yellow");
$("#content").load("files/shipments.html");
});
});

还有导航栏:

<div class="bar" id="nav">
<ul class="left">
<li><a href="#" id="request">Request Search</a></li>
<li><a href="#" id="catalog">Catalog Search</a></li>
<li><a href="#" id="publisher">Request from Publisher</a></li>
<li><a href="#" id="incoming">Catalog Incoming Files</a></li>
<li><a href="#" id="finished">Send Finished Files</a></li>
<li><a href="#" id="shipments">Shipments</a></li>
</ul>
</div>

最后但同样重要的是 CSS:

.bar { margin: 5px 0; position: relative; height: 20px; background-color: #515e6c; }
.bar a { color: #fff; }
.bar ul li a:hover { color: yellow; }
/* .bar ul li.active { color: yellow; } */
ul { margin: .3em 0; }
ul li { display: inline; padding: 0 5px; border-right: 1px solid #fff; }
ul li:last-child { border-right: none; }

提前致谢!

最佳答案

应该这样做:

$(document).ready(function () {
var $links = $('#nav ul li a');
$links.click(function() {
$links.css("color","white");
$(this).css("color","yellow");
$("#content").load("files/" + $(this).attr('id') + ".html");
});
});

就您选择的规则而言,将其更改为:

.bar ul li a.active { color: yellow; }

然后你可以把点击函数的前两行改成这样:

$links.removeClass('active');
$(this).addClass('active');

该样式最初应用于 <li>本身而不是 <a> .

关于javascript - 消除 jQuery 脚本中的冗余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/804087/

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