代码之家  ›  专栏  ›  技术社区  ›  Andrew

jQuery:当获取元素的值时,我需要在文档中声明变量吗?

  •  2
  • Andrew  · 技术社区  · 14 年前

    我将特定表单元素的值存储为变量。这个值在多个函数中使用。

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

    我想使它成为一个全局变量,这样我就不必在每个函数中一直选择它。所以我的问题是,如果我在documentready块之外声明变量,我还能正确地得到值吗?

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

    我想我可能已经回答了我自己的问题…可能在加载文档时值会发生变化。实际上,我要做的是删除重复的代码,在这里我多次得到元素的值。你对此有什么建议吗?

    2 回复  |  直到 14 年前
        1
  •  1
  •   Pointy    14 年前

    我建议 这样做。如果您想更快/更方便地访问,请编写一个函数:

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

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

    真正地 已经 (本质上)一个“全局变量”。该函数只是确保您没有执行“冗余”文档.getElementById()”调用(通过jQuery),但它保持了诚实,并避免了脚本“缓存”值不同步的潜在问题。

        2
  •  1
  •   Peter Ajtai    14 年前

    对。但是使用 var 只有一次,因为它声明了变量。

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

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