jquery - 寻找一种在 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 行这样的行,我认为只有一个来解决所有问题会更清楚。
解决方案
您在此处尝试遵循的模式被称为不要重复自己,或 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');
});
推荐阅读
- webpack - 属性选择器在生产环境中不能与 webpack 一起使用
- spring - Hibernate 异常:找到了不止一行具有给定标识符的行
- flutter - PageView 页面未释放,应用程序内存不足并崩溃
- mkdocs - 如何在 MKDocs 正文中“嵌入”自定义 404 页面?
- kotlin - 如何使用不同数据类的属性更新 kotlin 数据类
- arrays - 用于二维数组和按位运算的 C 到 MIPS 转换
- mysql - 如何通过最小值和最大值之间的计数获得最多 20 个组
- c++ - 如何编译 Quake 2 源代码
- vb.net - 拆分 PrintPage 的部分数量
- php - 想要禁用 error_log 中的警告,我尝试了所有可能的方法,但它不断出现