gpt4 book ai didi

javascript - 将 jQuery 对象传递给函数

转载 作者:行者123 更新时间:2023-11-29 19:59:11 24 4
gpt4 key购买 nike

这是 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/>

我试过这个,我认为它可以让我免于一次多次点击
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


附言:

我以前完全不同的尝试,使用 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;
});
});

最佳答案

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

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);
});
});

演示: http://jsfiddle.net/fjtFA/9/

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

关于javascript - 将 jQuery 对象传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com