hymn

忽有故人心头过,回首山河已是秋。

  menu
132 文章
0 浏览
3 当前访客
ღゝ◡╹)ノ❤️

js onclick第一次点击没反应,第二次才生效

点击 li 改变背景颜色,第一次点击没用

$(".type-list." + type + " ul li").on("click",function () {
        if (type == "category") {
            $(this).addClass("back-color").siblings().removeClass("back-color");
            if ($(this).hasClass("back-color")) {
                SearchPage.searchOption.type = '';
            } else {
                SearchPage.searchOption.type = id;
            }
        } else {
            $(this).addClass("back-color").siblings().removeClass("back-color");
            if ($(this).hasClass("back-color")) {
                SearchPage.searchOption.city = '';
            } else {
                SearchPage.searchOption.city = id;
            }
        }
    });

解决:

$("body").on("click", ".type-list." + type + " ul li",function () {
        if (type == "category") {
            $(this).addClass("back-color").siblings().removeClass("back-color");
            if ($(this).hasClass("back-color")) {
                SearchPage.searchOption.type = '';
            } else {
                SearchPage.searchOption.type = id;
            }
        } else {
            $(this).addClass("back-color").siblings().removeClass("back-color");
            if ($(this).hasClass("back-color")) {
                SearchPage.searchOption.city = '';
            } else {
                SearchPage.searchOption.city = id;
            }
        }
    });

绑定到class上

$(".type-list." + type + " ul li").on("click",function () {....})
// 替换为
$("body").on("click", ".type-list." + type + " ul li",function () {....})

标题:js onclick第一次点击没反应,第二次才生效
作者:hymn
地址:https://dxyhymn.com/articles/2020/06/09/1591681138807.html