我在一个 html 页面中使用了这 3 个函数:
$('#windowPanel1:first-child').children('div:eq(0)').click(function(){
$('#edit1').val("1");
});
$('#windowPanel1:first-child').children('div:eq(1)').click(function(){
$('#edit1').val("2");
});
$('#windowPanel1:first-child').children('div:eq(2)').click(function(){
$('#edit1').val("3");
});
我想要一个涵盖所有这些功能的功能。什么是最有效的方法?谢谢!
最佳答案
将事件绑定(bind)到 #windowPanel1:first-child
元素的所有直接后代 div
元素上。使用 index()
获取被点击元素的索引。返回的 index
是从零开始的索引。
$('#windowPanel1:first-child > div').click(function() {
$('#edit1').val($(this).index() + 1);
});
>
是 direct descendant/child selector它将返回与 .children('div')
相同的元素。
关于javascript - 使 JS 函数更高效和动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173187/