Javascript 可以被很多元素使用然后区分哪个元素点击了它的功能

Javascript function that can be used by many elements and then distinguish which element clicked it

例如,我有 12 个 div 标签,每个标签代表一个月。单击时,每个月份都会显示另一个 div 月份,并隐藏所有其他月份 divs

12 个月 div 有一个共同点 class month。每个包含该月内容的部分有 month_section 共同点,它们代表的月份名称不常见。

我的 javascript 代码:

$("#January,#February,#March,#April").click(function(e)){
  $(".month").removeClass("highlight");
  $(".month_sections").removeClass("show");
  $(".month_sections").addClass("hide");
  if(this == "#January"){(this).addClass("highlight");$(".january").addClass("show");}
  else if(this == "#February"){(this).addClass("highlight");$(".february").addClass("show");}
  else if(this == "#March"){(this).addClass("highlight");$(".march").addClass("show");}
  else if(this == "#April"){(this).addClass("highlight");$(".april").addClass("show");}
});

未正确检测到 if 语句

使用e.target,因为它指的是点击的元素。

请注意,这与使用 $(this) 不同。在这个问题的答案中阅读更多相关信息:Difference between $(this) and event.target?

使用以下作为您的 if 语句:

if ($(this).attr('id') === 'January')

如果您每个月都需要一些特别的东西,您也可以使用 switch 语句:

switch ($(this).attr('id'))
{
   case 'January':
   case 'February':
...
}

祝你好运!

在事件处理程序中,您试图将 this 对象与字符串进行比较。

jQuery 回调上下文中的 this 是被单击的元素。如果您想比较谁被点击了,您必须使用 this.id,这在第一个月的上下文中等于 January。所以你可以比较一下。

if(this.id == "January") {
    $(this).addClass("highlight");
    $(".january").addClass("show");
}

您可以采用其他一些方法来节省一些代码。

$("#January,#February,#March,#April").click(function(e) {
    var monthStr = this.id;

    $(".month").removeClass("highlight");
    $(".month_sections").removeClass("show");
    $(".month_sections").addClass("hide");

    $(this).addClass("highlight");
    $("." + monthStr.toLowerCase()).addClass("show");
});

希望有用。

你的代码有几个错误

您正在将 'this' 与元素的 ID 进行比较,这是 javascript 对象而不是元素的 ID

addClass 是一个 jQuery 方法,您必须将其称为“$(this)”

试试这个

$("#January,#February,#March,#April").click(function(e)) {
    $(".month").removeClass("highlight");
    $(".month_sections").removeClass("show");
    $(".month_sections").addClass("hide");
    if (this.id == "January") {
        $(this).addClass("highlight");
        $(".january").addClass("show");
     } 
    else if (this.id == "February") {
        $(this).addClass("highlight");
        $(".february").addClass("show");
    } 
    else if (this.id == "March") {
        $(this).addClass("highlight");
        $(".march").addClass("show");
    } 
    else if (this.id == "April") {
        $(this).addClass("highlight");
        $(".april").addClass("show");
    }
});

注意:如果您使用 e.target.id 或 $(this).attr('id') 而不是 this.id,这些都应该有效