gpt4 book ai didi

jquery - 如何编写简短的非特定于元素的 jquery?重复代码头痛

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:35 25 4
gpt4 key购买 nike

我不得不为每个元素复制代码。这是一个例子,如果输入元素有一定的左边距,它会说输入元素有一定的左边距,然后将第一个输入移开并显示第二个 [.next()] .. 然后是第三个/第四个等等 - 不需要重复代码。

var input1 = $(".input-one");
var input2 = $(".input-two");

$(document).keypress(function(e) {
if(e.which == 13) { // on enter press
if ($(input1).css("margin-left") === "-232px") { // if input has this margin
$(input1).css({"margin-left":"-1200px","opacity":"0"}); // move input left and fade out
$(input1).next().css({"display":"block"}); // show next input
setTimeout(function() {
$(input1).next().css({"margin-left":"-232px","opacity":"1"}); // animate next input in
}, 40);
setTimeout(function() {
$(input1).next().focus() // focus next input
$(input1).css({"display":"none"}); // hides first input after fade out
}, 600);
}
if ($(input2).css("margin-left") === "-232px") {
// DUPLICATE CODE WOULD BE HERE
}
}
});

我试过:

var input1 = $("#input-container").children();

但这会将 css 属性应用于所有按回车键的 child ,这是不需要的。我需要这样的东西:

if ($(input1).css("margin-left") === "-232px") { // if input has this margin
$(this input1).css({"margin-left":"-1200px","opacity":"0"}); // affect only the initial if input NOT all of the children

但这就是我的知识结束的地方。我不想重复代码并将其编写为适用于每个输入更改,影响 -232px margin-left 的当前输入。

希望这是有道理的,非常感谢

最佳答案

将它们全部存储在一个 jQuery 对象中,然后使用 .each() 将您的逻辑依次应用到它们中的每一个:

var elements = $('#input-container').children();

$(document).keypress(function(e) {
if(e.which == 13) { // on enter press
elements.each(function() {
var $input = $(this); // the specific element for this iteration
if ($input.css("margin-left") === "-232px") { // if input has this margin
$input.css({"margin-left":"-1200px","opacity":"0"}); // move input left and fade out
$input.next().css({"display":"block"}); // show next input
setTimeout(function() {
$input.next().css({"margin-left":"-232px","opacity":"1"}); // animate next input in
}, 40);
setTimeout(function() {
$input.next().focus() // focus next input
$input.css({"display":"none"}); // hides first input after fade out
}, 600);
}
});
}
});

关于jquery - 如何编写简短的非特定于元素的 jquery?重复代码头痛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23805860/

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