首页 > 解决方案 > 寻找一种在 jquery 中“参数化” .click() 的方法

问题描述

因为我远不是一个 jquery 新手(我接管了一堆代码,现在需要一种方法来弄清楚它是如何工作的以及如何改进它),我有以下代码:

jQuery:

$("#button1").click(function() {$("#btnbutton1:first-child").click();});
$("#button2").click(function() {$("#btnbutton2:first-child").click();});
$("#button3").click(function() {$("#btnbutton3:first-child").click();});

HTML:

<DIV class=hiddenButtons>
<div id="btnbutton1"><SpotfireControl id="2e21a4f7e5794ad98b0048672462a290" /></div>
<div id="btnbutton2"><SpotfireControl id="0f8b33874ec64a4285721f11b42373db" /></div>
<div id="btnbutton3"><SpotfireControl id="0ae43a8ccc784fa192dbc360431a912f" /></div>
</DIV>
[....]
        <td id="button1" class="button-group active">Label1</td>
        <td id="button2" class="button-group">Label2</td>
        <td id="button3" class="button-group">Label3</td>
[....]

我想要实现的是一种将 jquery 优化为类似于以下的一行的方法:

$("#"+param).click(function() {$("#btn"+param+":first-child").click();});

换句话说:有没有办法将此jQuery缩短为一行,在单击对象后将其ID传递给jQuery,然后执行单击操作?问我的 jQuery 最终会得到大约 20 行这样的行,我认为只有一个来解决所有问题会更清楚。

标签: jquery

解决方案


您在此处尝试遵循的模式被称为不要重复自己,或 DRY。

为了实现这一点,您可以使用td元素上的公共类对它们进行分组,并使用data属性向它们中的每一个添加一些自定义元数据以更改点击事件行为。像这样的东西:

<div class="hiddenButtons">
  <div id="btnbutton1">
    <SpotfireControl id="2e21a4f7e5794ad98b0048672462a290" />
  </div>
  <div id="btnbutton2">
    <SpotfireControl id="0f8b33874ec64a4285721f11b42373db" />
  </div>
  <div id="btnbutton3">
    <SpotfireControl id="0ae43a8ccc784fa192dbc360431a912f" />
  </div>
</div>

<td class="button-group active" data-target="#btnButton1">Label1</td>
<td class="button-group" data-target="#btnButton2">Label2</td>
<td class="button-group" data-target="#btnButton2">Label3</td>
$(".button-group").click(function() {
  var selector = $(this).data('target');
  $(selector).find(':first-child').trigger('click');
});

推荐阅读