gpt4 book ai didi

javascript - jQuery:变量 ID 不更新

转载 作者:行者123 更新时间:2023-11-30 09:52:26 26 4
gpt4 key购买 nike

我想要一个按键功能,可以更改光标在输入字段中的位置。当 jQuery id 只是“body”但 keydown 无处不在时它起作用。相反,我希望 keydown 仅在最近生成的输入字段中起作用。请参阅下面的代码。

var ui_pc = 3001;

$(document).ready(function () {
$("#"+ui_pc+"input").keydown(function(e){
var press = e.which;
press = press.toString();
if(e.which=="13") {
ui_pc++;
$("#main").append("<div id=\"" + ui_pc + "\"><input id=\""+ ui_pc+ "input\"></input></div>");
document.getElementById(ui_pc+"input").focus();
}
});
});

由于光标从第 3001 行开始,当您将光标放在那里时,它可以正常工作。但是,该函数不会更新,即该函数仅适用于 div“#3001input”,并且不会使用名为 pc_ui 的变量进行更新。

为什么会这样?我认为这与 JS 中的闭包有关?

最佳答案

您必须更改为委托(delegate)事件方法:

$(document).on('keydown', '[id$="input"]', function(e){
//your stuff
});

为什么会这样?

这是因为您在 DOM 准备就绪时将事件附加到现有元素,而不是为创建的新元素附加事件。为避免这种情况,请使用此委托(delegate)方法并且它有效。

查看更多:

https://learn.jquery.com/events/event-delegation/

关于javascript - jQuery:变量 ID 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699211/

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