[英]Any Ideas how to optimize my small Jquery Code for a menu?
I have 3 divs(#carta1,#carta2 and #carta3) that are hidden (display:none), each one with different information. 我有3个div(#carta1,#carta2和#carta3)被隐藏(显示:无),每个div具有不同的信息。 When the user goes over a navigation bar the corresponding div is shown. 当用户越过导航栏时,将显示相应的div。
It works fine but i think its to much code.. is there any way to make it simpler(for example to use only 1 function)? 它工作正常,但我认为它的代码很多。是否有任何方法可以使其更简单(例如仅使用1个函数)?
thanks for the help! 谢谢您的帮助!
here´s my Jquery code: 这是我的Jquery代码:
$("#frueh, #carta1").hover(function (e) {
e.preventDefault();
$("#carta1").stop().fadeIn();
},
function(){
$("#carta1").stop().fadeOut(750);
});
$("#sup, #carta2").hover(function (e) {
e.preventDefault();
$("#carta2").stop().fadeIn();
},
function(){
$("#carta2").stop().fadeOut(500);
});
$("#sal, #carta3").hover(function (e) {
e.preventDefault();
$("#carta3").stop().fadeIn();
},
function(){
$("#carta3").stop().fadeOut(750);
});
and here´s the Html list: 这是HTML列表:
<ul id="speise">
<li><a id="frueh" href="">Frühstück</a></li>
<li><a id="sup" href="">Suppen</a></li>
<li><a id="sal" href="">Salate</a></li>
</ul>
Whenever you have repeated code like that, it's usually a sign that you could put it into a function. 每当您重复这样的代码时,通常就表示您可以将其放入函数中。
function registerHoverListener(triggerElementId, displayElementId, fadeoutTime) {
var fadeIn = function(e) {
e.preventDefault();
$(displayElementId).stop().fadeIn();
};
var fadeOut = function() {
$(displayElementId).stop().fadeOut(fadeoutTime);
};
$(triggerElementId, displayElementId).hover(fadeIn, fadeOut);
});
registerHoverListener("#sup, #carta2", 500);
registerHoverListener("#sal, #carta3", 750);
registerHoverListener("#frueh, #carta1", 750);
You may be able to remove the fadeoutTime
param if you only want it to be 750 in all the cases. 如果仅在所有情况下都希望将其设置为750,则可以删除fadeoutTime
参数。 I didn't know if that 500 was a typo. 我不知道那500是不是错字。
thataustin's answer works well, another option would be to target down to your ul children, then grab the id from the event. thataustin的答案效果很好,另一种选择是将目标锁定在您的孩子身上,然后从事件中获取ID。 Something like: 就像是:
$("#speise > li > a").hover(function (e) {
e.preventDefault();
alert(e.target.id);
});
Then you could make data tags or target children further to perform your desired actions, depending on where #carta1
, #carta2
, and #carta3
are located. 然后,您可以根据#carta1
, #carta2
和#carta3
的位置,制作数据标签或进一步定位子项以执行所需的操作。
Again, Austin's answer is easier to implement and easier to read, just food for thought. 同样,奥斯汀的答案更易于实现和阅读,只是值得深思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.