如何将参数传递到事件处理程序中以使其唯一

how to pass arguments into an event handler to make it unique?

本文关键字:唯一 程序 事件处理 参数传递      更新时间:2023-09-26

请运行这个jsfiddle作为示例。

http://jsfiddle.net/AFzqt/11/

在我的示例中,我有一个链接,上面说相同,如果您填写第一个框,它将复制第二个框中的值。 查看代码,并查看显示。 重复代码只是为了让框出现两次。 嗯......在我实际使用它时,理想情况下,我希望有大约 40 个这样的按钮。

有没有办法在不复制代码 40 次的情况下做到这一点?我是 jQuery 的新手,通常在另一种语言中我只会传入参数,但使用这种语法,我不明白我该怎么做?我该如何处理?

随意涉足我的 JSFIDDLE,并希望链接一个新的修订版,目的是将这两个"与上面相同"按钮的处理减少到一个以条目 ID 作为参数的函数中

如果将

changeButton 类添加到每个按钮,则更容易选择每个按钮来绑定事件处理程序:

<a href="#" class="changeButton">Same as Above</a>

然后我们可以像这样选择每个元素:

$(".changeButton").on("click", function(e) {
    //select the previous jQuery Mobile select widgets, we will use just the previous two
    var $allPrev = $(this).prevAll('.ui-select').find('select');
    //change the value of the immediate previous select widget to the value of the one preceding it
    $($allPrev[0]).val($($allPrev[1]).val()).selectmenu("refresh");
    e.preventDefault();
});

这是一个演示:http://jsfiddle.net/AFzqt/12/

此代码适用于无数按钮,因为它通过使用 HTML 结构的直观知识来工作(每个链接都使用前两个选择小部件,无论链接位于页面上的哪个位置)。

这样的事情呢?

function bind_click(button_id, target_id, origin_id) {
  $(button_id).on("click", function(e) {
    $(target_id).val($(origin_id).val());
    $(target_id).selectmenu("refresh");
    e.preventDefault();
  });
}
$(function() {
  bind_click("#changeButton2", "#entry_20", "#entry_18");
  bind_click("#another", "#entry", "#entry2");
  // More binding declarations
});