gpt4 book ai didi

javascript - 调整大小后尝试将 jquery 设置为触发一次

转载 作者:行者123 更新时间:2023-11-29 20:48:19 24 4
gpt4 key购买 nike

有没有办法在调整大小时只触发一次 jquery?我这里有一个添加 hash(#) 的脚本在 href 内的 anchor <a>元素。问题是脚本在调整大小时保持不变,因此它不断添加 hashhref 内.有没有办法让它只触发一次?

(function($){
'use strict';



var mobileMenuDrawer = {

init : function() {

$('.region-primary-menu').addClass('primary-mobile-menu');
$('.primary-mobile-menu .menu.-primary > .menu-item').addClass('mobile-menu-item');
$('.primary-mobile-menu .menu.-primary > .mobile-menu-item > .link').off('click').on('click', function() {
$(this).closest('.mobile-menu-item').toggleClass('-active');
})
},

clear : function() {
$('.primary-mobile-menu, .mobile-menu-item').removeClass('primary-mobile-menu mobile-menu-item');
}
}

var addHash = {

init : function() {

if ($('.region-primary-menu').hasClass('primary-mobile-menu')) {

$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {
// console.log($(this).attr('href'));
let currentUrl = $(this).attr('href');

$(this).prop('href', '#' + currentUrl);

// this.href = '/#/' + this.href;
// window.location.hash = $(this).attr('href');
});
}

else {

$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {

$(this).removeAttr('#');

});

}
}
}


$(document).ready(function() {

if ($(window).outerWidth() <= 1024) {
mobileMenuDrawer.init();
}

else {
mobileMenuDrawer.clear();
}

addHash.init();


});

$(window).on('resize', function() {

if ($(window).outerWidth() <= 1024) {
mobileMenuDrawer.init();
addHash.init();
}

else {
mobileMenuDrawer.clear();
}
});



})(jQuery)

最佳答案

是的。只需放置一个标志来检查该属性是否已存在:

if(!$(this).prop('href')) {
$(this).prop('href', '#' + currentUrl);
}

或者如果属性相似:

if($(this).prop('href') != '#' + currentUrl) {
$(this).prop('href', '#' + currentUrl);
}

或者如果该属性为空(仅当该属性已存在时才有效):

if($(this).prop('href') == "") {
$(this).prop('href', '#' + currentUrl);
}

如果你想阻止整个代码块的执行。您可以使用某种自定义标志,一旦所需的操作完成,您需要将其轻弹到相反的 bool 值。您可以将其设为本地函数范围内的变量,或将其设为 addHash 对象的属性。我会在这一个中做前者。

 let isOk = false;

var addHash = {

init : function() {
if(isOk) return;

if ($('.region-primary-menu').hasClass('primary-mobile-menu')) {

$('.primary-mobile-menu .mobile-menu-item > .link').each(function() {
let currentUrl = $(this).attr('href');

$(this).prop('href', '#' + currentUrl);
isOk = true;
});
}
}
}

注意:您应该停止使用 var。

关于javascript - 调整大小后尝试将 jquery 设置为触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291352/

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