简体   繁体   English

jQuery为DOM中尚不存在的元素定义全局变量

[英]jQuery Define a Global Variable for an element that does not yet exist in DOM

I'm working on a page where user can create a form by clicking to insert fields. 我正在处理一个页面,用户可以通过单击插入字段来创建表单。 Initially no input elements exist on the page. 最初页面上不存在任何输入元素。 User clicks to created them. 用户点击以创建它们。 I'm trying to create Global variables to reference those input fields so i can later make use of this, but since input fields do not initially exist in DOM, the global variable is giving undefined. 我正在尝试创建全局变量来引用那些输入字段,以便稍后我可以使用它,但由于输入字段最初不存在于DOM中,因此全局变量给出了undefined。 Anyway way around this. 无论如何,这周围的方式。 I want the variables to be global, because i want to make use of them in other functions. 我希望变量是全局的,因为我想在其他函数中使用它们。

Ex: 例如:

var $selected = $('#form').find('.selected input').val(); //Global variable outside the function. Since this doesn't initially exist in DOM, it's giving undefined. 

If the collection of the INPUTs changes, why do you want it to be statically captured in a variable? 如果INPUT的集合发生变化,为什么要在变量中静态捕获它? Just select them each time you need them. 只需在每次需要时选择它们。

You can reference the same variables everywhere. 您可以在任何地方引用相同的变量。 However, the catch being that since the DOM is initially empty, you have to populate those variables when a user creates these objects. 但是,由于DOM最初是空的,因此必须在用户创建这些对象时填充这些变量。

var $selected;

Say when the user clicked a button to insert an input element. 假设用户单击按钮以插入输入元素。 The $selected variable has to be updated at this time. $selected变量必须在此时更新。

function addTextInput() {
    var input = $('<input type="text" value="awesome" />');
    $("form .selected").append(input);

    // the global variable is being updated now.
    $selected = $('#form .selected input').val();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM