gpt4 book ai didi

javascript - jquery 检查类问题,

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

我有一个按钮,根据类值应该向 POST 发送不同的值,但是无论发生什么,它都只运行一个条件,无论我做什么,我只能让它向 POST 发送方法=添加数据。

这是我的代码

$("a.navlink").click(function (ev) {
$(this).removeClass("active");
var url = $(this).attr("href")
ev.preventDefault();
if($('a.navlink:not(.active)')) {

$.ajax ({
url: url,
type: "POST",
data: "method=add",
success : function (html) {
$('#accordion').accordion('destroy');
$("#accordion").append(html);
$('#accordion').accordion({
active: 0,
header:'h2.Blog'
});
//alert(accordion())
}
});
}
if ($(this).hasClass("active")) {
// $(this).addClass('active')
$.ajax ({
url: url,
type: "POST",
data: "method=delete",
success : function (html) {
alert("hello")
$(this).removeClass('active')
//alert(accordion())
}
});
}


});

基本上我需要的是,如果单击按钮时它会添加一个名为 active 的类并且 ajax 运行,当再次单击它时,需要删除该类并运行 ajax,这可能吗?

最佳答案

您现在在第一个 if 子句中所做的基本上是检查 $('a.navlink:not(.active)') 是真还是假 – $() 总是返回一个计算结果为 true 的对象。您也应该对其执行 hasClass。而且您要删除 if 之前的“active”类,那么您以后如何比较它?

不清楚您要做什么,但您想要的可能是这样的:

$("a.navlink").click(function(ev) {
var url = $(this).attr("href")
ev.preventDefault();
// If the link is not active, run 'add':
if(!$(this).hasClass('active')) {
$.ajax ({
url: url,
type: "POST",
data: "method=add",
success: function (html) {
$('#accordion').accordion('destroy');
$("#accordion").append(html);
$('#accordion').accordion({
active: 0,
header:'h2.Blog'
});
}
});
// Mark it as active
$(this).addClass('active');
// If the link is active, run 'delete':
} else {
$.ajax ({
url: url,
type: "POST",
data: "method=delete",
success: function (html) {
alert("hello")
}
});
// Unmark it.
$(this).removeClass('active');
}
});

该代码的用途对我来说意义不大,如果我理解错了请告诉我。

关于javascript - jquery 检查类问题,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2049249/

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