gpt4 book ai didi

javascript - 变量的Jquery问题

转载 作者:行者123 更新时间:2023-11-29 18:19:54 27 4
gpt4 key购买 nike

我有以下示例:http://jsfiddle.net/gespinha/yTjUL/13/

该变量应在点击 时触发,使链接类从on 更改为off 并将颜色从红色更改为绿色。但相反它开始时已经是绿色的,因此使该功能无用。

为什么不起作用?

HTML

<a id="link" href="javascript:void(0)" class="on">CLICK HERE</a>

JQUERY

$(document).ready(function () {

var $myVar = $(document).find('.on').addClass('off').removeClass('on');
$('link').click(function () {
$myVar
});

});

最佳答案

您的印象似乎是变量将存储一系列操作,以便稍后在“调用”变量时执行,但这不是(清楚地)发生的事情:第一行,在 ready () 处理程序,在 var 赋值中,找到 .on 元素并执行您指定的操作,存储 .on变量中的元素(因为 jQuery 方法几乎都返回 this 对象)。

相反:

$(document).ready(function () {
// use the `#link` notation, since 'link' is the id of the element:
$('#link').click(function () {
// assign a function to the click-event handler:
$('.on').addClass('off').removeClass('on');
});
});

或者,更简单(如果你想在“状态”之间切换)使用 toggleClass()$(this)(而不是从整个每次用户单击给定元素时记录):

$(document).ready(function () {
$('#link').click(function () {
$(this).toggleClass('on off');
});
});

此外,不要在 href 中使用 javascript:void(0),只需使用 jQuery 来阻止默认操作,使用:

$(document).ready(function () {
$('#link').click(function (e) {
e.preventDefault();
$(this).toggleClass('on off');
});
});

JS Fiddle demo .

引用资料:

关于javascript - 变量的Jquery问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19736682/

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