将jQuery对象传递给函数

时间:2013-03-04 18:40:09

标签: javascript jquery

这是我想要实现的working demo。只需在输入中输入一些值,您就可以得到我想要达到的效果。 (是的,我让它工作但继续......)
但是当多个按键被按在一起时它会失败。

我在尝试什么:
 我的屏幕包含少数启用和少数禁用的输入元素。每当用户更新可编辑输入元素中的任何值时,我想更新具有与用户更新值相同值的禁用输入。

HTML:

<input value="foo" />   // When User updates this
<br/>
<input value="bar">
<br/>
<input value="Hello">
<br/>
<input value="World">
<br/>
<input value="foo" disabled>  // this should be updated
<br/>
<input value="bar" disabled>
<br/>
<input value="foo" disabled>  // and this also
<br/>
<input value="bar" disabled>
<br/>
<input value="Happy Ending!">
<br/>  

我尝试了这个,我认为这将使我免于multip_clicks_at_a_time
JS:

$(":input:not(:disabled)").keyup(function () {
    // Get user entered value
    var val = this.value;

    // Find associated inputs which should be updated with new value
    siblings = $(this).data("siblings");
    $(siblings).each(function () {
         // Update each input with new value 
         this.value = val;
    });
});

$(function () {
    $(":input:not(:disabled)").each(function () {
        // Find inputs which should be updated with this change in this input
        siblings = $(":input:disabled[value=" + this.value + "]");

        //  add them to data attribute   
        $(this).data("siblings", siblings);
    });
});

但是我无法将选择器传递给keyup函数并在其上调用.each


PS:

我之前完全不同的尝试,使用single_click_at_a_time但我觉得我不必要地一遍又一遍地遍历DOM所以放弃了这个

$(":input").keypress(function () {
    $(this).data("oldVal", this.value);
});

$(":input").keyup(function () {
    var oldVal = $(this).data("oldVal");
    $(this).data("newVal", this.value);
    var newVal = $(this).data("newVal");

    $("input:disabled").each(function () {
        if (this.value == oldVal) this.value = newVal;
    });
});

2 个答案:

答案 0 :(得分:2)

我会先对这些输入进行分组,并为已启用的元素绑定一个处理程序以应用于该组。见下文,

var grpInp = {};

$(":input").each(function () {
    if (grpInp.hasOwnProperty(this.value)) {
        grpInp[this.value] = grpInp[this.value].add($(this));
    } else {
        grpInp[this.value] = $(this); 
    }
});

$.each(grpInp, function (i, el) {    
    el.filter(':enabled').keyup(function () {
        el.val(this.value);
    });
});

DEMO: http://jsfiddle.net/fjtFA/9/

上述方法基本上将输入元素分组为相同值,然后根据:enabled过滤它们并绑定处理程序以将其应用于组。

答案 1 :(得分:1)

// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings", siblings);

没有。使用两个参数调用的.data method无法获取,但设置数据(并返回当前选择)。此外,您应该将变量设为本地:

var siblings = $(this).data("siblings");

Working demo

相关问题