开发者

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

开发者 https://www.devze.com 2023-02-18 09:06 出处:网络
I\'m working on a page where user can create a form by clicking to insertfields. Initially no input elements exist on the page. User clicks to created them. I\'m trying to create Global variables to r

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, bu开发者_如何学编程t since input fields do not initially exist in DOM, the global variable is giving 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. 


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.

var $selected;

Say when the user clicked a button to insert an input element. The $selected variable has to be updated at this time.

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


If the collection of the INPUTs changes, why do you want it to be statically captured in a variable? Just select them each time you need them.

0

精彩评论

暂无评论...
验证码 换一张
取 消