gpt4 book ai didi

javascript - jQuery 点击运行一个函数,再次点击运行另一个

转载 作者:行者123 更新时间:2023-11-30 12:32:00 26 4
gpt4 key购买 nike

我正在尝试运行一小段 jQuery - 单击它时它会运行一个函数,再次单击它会运行另一个函数。

我尝试了以下方法,但这甚至没有运行第一个。

$('body').on('click', '.card--small', function() {
console.log('clicked');
$(this).addClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
}, function() {
console.log('clicked again');
$(this).removeClass('card--expanded');
if (topCheck() == 'chrome') {
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
});

function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1) {
if (ua.indexOf('chrome') > -1) {
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}

最佳答案

只需使用 card--expanded 类作为标志来确定您需要的点击并相应地设计您的功能。

$('body').on('click', '.card--small', function (e) {
var self = $(this),
isExpanded = self.hasClass('card--expanded'),
isChrome = topCheck() === 'chrome'; // will always be false as topCheck never returns 'chrome' (it returns either 'safari' or undefined).
self.toggleClass('card--expanded', !isExpanded);
if (!isExpanded) {
console.log('clicked');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '51px'
});
}
} else {
console.log('clicked again');
if (isChrome) { // will never execute as isChrome will always be false
$('.card--expanded .card--small__container').css({
'top': '0'
});
}
}
});

重点是使用一些外部条件作为标志来跟踪点击状态。这可以是全局变量,也可以是范围链中处理程序上方的局部变量(或 CSS 类或 HTML5 数据属性等)。有多种方法可以做到这一点。使用 CSS 类似乎很适合您的情况。

此外,topCheck 函数如果有机会返回 'chrome' 会更好:

function topCheck() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
return 'chrome';
console.log('Chrome');
} else {
return 'safari';
console.log('Safari');
}
}
}

function topCheck() {
var ua = navigator.userAgent.toLowerCase(),
browser = 'unknown';
if (ua.indexOf('safari') > -1) {
if (ua.indexOf('chrome') > -1) {
browser = 'chrome';
console.log('Chrome');
} else {
browser = 'safari';
console.log('Safari');
}
}
return browser;
}

就个人而言,我不喜欢每个函数有多个返回语句,所以我会使用第二种形式。

关于javascript - jQuery 点击运行一个函数,再次点击运行另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427278/

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