gpt4 book ai didi

javascript - jQuery:简单的菜单

转载 作者:行者123 更新时间:2023-11-29 15:05:59 26 4
gpt4 key购买 nike

我正在尝试通过实现一个简单的菜单来学习 jQuery。我有 <div>充当按钮并具有链接的元素。我正在尝试将 onclick 事件添加到将浏览器导航到 div 中链接地址的 div。这基本上是我的伪代码。真正的代码是什么?我该如何改进呢?感谢任何反馈!

// Iterate over each menu button

$('.masterHeaderMenuButton').each(function () {

// Get the link in each button and set the button's onclick to
// redirect to the link's address

var url = $('a', this).attr('href');

this.click(function () {
window.location.href = url;
});

// If the user is on the page for the current button, hilight it

if (window.location.href === url) {
$('a', this).addClass("masterHeaderMenuButtonSelected");
}
});

最佳答案

试试这个未经测试的例子:

$('.masterHeaderMenuButton a').each(function () {

// Get the link in each button and set the button's onclick to
// redirect to the link's address

var _this = this; // save this ref for click handler.
$( this ).parent().click(function () {
window.location.href = $(_this).attr('href');
});

// If the user is on the page for the current button, highlight it

if (window.location.href === url) {
$(this).addClass("masterHeaderMenuButtonSelected");
}
});

关于javascript - jQuery:简单的菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2742449/

26 4 0