开发者

jQuery: When getting the value of an element, do I need to declare the variable in document ready?

I'm storing the value of a specific form element as a variable. This same value is used in multiple functions.

function one() {
    var selectedRole = $('#RegistrationRole_ID').val();
}
function two() {
    var selectedRole = $('#RegistrationRole_ID').val();
}

I'd like to make this a global variable so I don't have to keep selecting it in each of my func开发者_StackOverflow中文版tions. So my question is, am I able to still get the value correctly if I declare the variable outside of my document ready block?

<select id="RegistrationRole_ID">
    <option value="1">one</option>
</select>

I think I might have answered my own question...it's possible that the value may change from when the document is loaded. Really, what I am trying to do is remove duplicate code, where I get the value of the element multiple times. Do you have a suggestion for this?


I would suggest not doing that. If you want quicker/easier access, write a function:

var getRoleId = (function() {
  var roleField = $('#RegistrationRole_ID').get(0);
  return function() {
    return roleField.value;
  };
})();

Now you can write

  if (getRoldId() == 22) { // whatever }

The advantage is that you're really not repeating yourself: that role field, with it's global unique "id" value, is already (in essence) a "global variable". The function just makes sure you're not performing redundant "document.getElementById()" calls (via jQuery), but it keeps thing honest and avoids potential problems of the script "cached" value getting out-of-sync.


Yes. But use var only once, since it declares the variable.

var selectedRole; // selectedRole is now global.
function one() {
    // If one() is called after doc ready
    // selectedRole will be $('#RegistrationRole_ID').val();
    // in it.
}
function two() {
    // If two() is called after doc ready
    // selectedRole will be $('#RegistrationRole_ID').val();
    // in it.
}
$(function() {
    selectedRole = $('#RegistrationRole_ID').val();  // This change that global
    // Now you can use one() and two() w/o redoing the same jQuery
    // over and over again.
    one(); two();
});

A better option. Just use a big enough scope for all your variables / functions with a self executing anonymous function:

(function() {
    var selectedRole; // selectRole is now available everywhere in the anon fun()
                      //   but it is not global
    function one() {
        ...
    }
    function two() {
        ...
    }

    $(function() {
        selectedRole = $('#RegistrationRole_ID').val();  // Change the variable
        // Now you can use one() and two() and
        // selectedRole will be available:

        one(); two()
    });
}());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜