我是 Javascript 和 Jquery 新手,我遇到了一个小问题。
我试图确保如果给定的链接存在,则将鼠标悬停在该链接上将弹出一个带有 fadeToggle() 的弹出窗口。
所以我编写了这段有效的代码:
if ($('.link-1')) {
$('.link-1').mouseover(function () {
$('.popup-1').fadeToggle();
})
.mouseout(function () {
$('.popup-1').fadeToggle();
})
}
但是,我不想重复十次,而是想编写一个循环,如下所示:
var number = 0;
while (number < 10) {
var popup = '.popup-' + number;
var link = '.link-' + number;
if ($(link)) {
$(link).mouseover(function () {
$(popup).fadeToggle();
})
.mouseout(function () {
$(popup).fadeToggle();
})
}
number++;
}
但是它不起作用。你能帮我一下吗?
我先谢谢你了!
最佳答案
根据您的评论,我推荐这种方法。
向与您要触发的弹出窗口相对应的每个链接添加数据属性。这看起来像这样:
<a href='#' class='link-1' data-popup='popup-1'> Link </a>
然后向所有链接添加一个悬停事件,如果具有以下数据类型,则执行操作:
//hover event on all links(assumes anchor tags)
$('a').mouseover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
.mouseout(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
如果适合您的用例,您还可以使用 .hover 而不是 .mouseover 和 .mouseout 将其设为单行函数
**此处添加重构过程:
//start with the original function
$('a').hover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
//consolidate the enter and exit events using .hover()
$('a').hover(function () {
if ($(this).attr('data-popup')) {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
}})
//remove the if statement, because the function firing without a pop up won't result in any effect
$('a').hover(function () {
let popup = '.' + $(this).attr('data-popup');
$(`${popup}`).fadeToggle();
})
//substitute the variable directly into the jquery tag
$('a').hover(function () {
$(`'.${$(this).attr('data-popup')}`).fadeToggle();
})
// use an ES6 arrow function to make this a one line function
$('a').hover(() => $(`.${$(this).attr('data-popup')}`).fadeToggle())
//as is, this function won't work, because the arrow function binds the "this" keyword differently.
//Event handlers have an optional parameter that is an event JSON object, so we pass that into the function.
//Because it is a parameter, and is used as a variable we can call event "e" for short
//target is a property of the JSON object 'event' that indicates what specific element is triggering the event
// You can console log "e" to see what other values are baked into the event
$('a').hover((e) => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
//lastly, because we are using an anonymous arrow function with only one parameter, we can omit the parenthesis around the paremeter
$('a').hover(e => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
最终结果是下面的一行!
$('a').hover(e => $(`.${$(e.target).attr('data-popup')}`).fadeToggle())
有关数据属性的其他信息可以在此处找到:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
关于javascript - 如何使用 Jquery 循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095373/