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

时间:2012-04-16 18:34:10

标签: javascript jquery jquery-mobile

请以此jsfiddle为例。

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

在我的例子中,我有一个与上面相同的链接,如果你填写第一个框,它将复制第二个框中的值。看一下代码,然后看一下显示。重复一下代码,只是让框出现两次。嗯...在我真正使用它的时候,我理想地希望有大约40个按钮。

有没有办法在不复制代码40次的情况下执行此操作? 我是jquery的新手,通常用另一种语言我会传递参数,但是用这种语法我不知道我怎么能这样做?我怎么处理这个?

随意浏览我的jsfiddle,并希望链接一个新版本,目标是将那些2'与上面的'按钮相同的处理减少到只有一个函数,条目id为参数

2 个答案:

答案 0 :(得分:3)

如果将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结构的直观知识(每个链接使用前两个选择的小部件,无论链接所在的页面位于何处)。

答案 1 :(得分:0)

这样的事情怎么样?

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
});
相关问题