首页 > 解决方案 > 如何动态使用jQuery切换方法?

问题描述

在我的项目中,需要大量的 jQuerytoggle来改变文本和图标。现在我正在使用:

$("#id1").click(function () {
  //Code to toggle display and change icon and text
});

$("#id2").click(function () {
  //Same Code to toggle display and change icon and text as above except change in id
});

问题是我要切换的代码太多了,代码很长,但我为每个代码更改的只是 id。所以我想知道是否有任何方法可以使这变得简单。

下面是一个示例图片。我在单页中得到了更多。

复选框

标签: javascriptjqueryhtmltoggle

解决方案


哦,你能用 aclass代替id吗?

<ul>
  <li class="idx">A</li>
  <li class="idx">B</li>
  <li class="idx">C</li>
</ul>
$(".idx").click(function(e){
   //Code to toggle display and change icon and text
  let target = e.target;
  //You can do all what you want just base on the `target`;
});

推荐阅读