将一个 div 的相同更改应用到另一个 div

Applying the same changes for one div to another div

以下代码对 .main 内部的 class1 及其 (class1) 内容进行了一些更改。

$('.main').on('click','.class1',function(){
   //some work with $(this)
});

此外,.main 内部有一个 div.class2,其结构与 div.class1 相似。

问题是: 通过单击 .class1 将上述代码对 class1 发生的所有更改应用到 class2 的最简单方法是什么?

克隆 div.class1div.class2 不是正确的方法,因为内容略有不同。只有上面正在执行的代码应该同时应用于 class1class2.

重要的是上面的代码包含 .closest() 这样的方法 $(this).closest('.bar').

您可以使用逗号组合多个选择器:

$('.main').on('click','.class1, .class2',function(){
   //some work with $(this)
});

但我想推荐你为他们使用一个通用的class。

$('.main').on('click','.common_class',function(){
   //some work with $(this)
});

您可以在 html 中使用多个 class,方法是在它们之间放置一个 space。

例如:

<div class="class1 common_class"></div>
<div class="class2 common_class"></div>