在按钮单击中使var值可用

时间:2012-07-06 17:10:13

标签: javascript jquery-ui jquery

如何在var mydomain中获取域的值= collectDomains [i] .email_domain在稍后的按钮点击事件中可用

$(document).ready(function() {
$('#email_address').blur(function(){

        var emailAddress = $('#email_address').val().split('@');
        var domain = emailAddress[1];
        var tagMap = {};
           var i = null;
        for (i = 0; collectedDomains.length > i; i += 1) {
            var mydomain = collectedDomains[i].email_domain;               
        }

        var hasTag = function(tagName) {
            return tagMap[tagName];
        };  

    $('#Button1').click(function(){
        //need the value of var mydomain available here
    });
});

3 个答案:

答案 0 :(得分:2)

这是一个范围问题。您只需要在引用它的两个函数之外定义要使用的变量。像这样:

$(document).ready(function() {
    var mydomain = null;

    $('#email_address').blur(function(){

        var emailAddress = $('#email_address').val().split('@');
        var domain = emailAddress[1];
        var tagMap = {};
        var i = null;

        for (i = 0; collectedDomains.length > i; i += 1) {
            mydomain = collectedDomains[i].email_domain;               
        }

        var hasTag = function(tagName) {
            return tagMap[tagName];
        };  
    });

    $('#Button1').click(function(){
        //mydomain equals whatever you set it to in the .blur call
    });
});

答案 1 :(得分:1)

$(document).ready(function() {

var domain;
// domain is now available in all the functions inside ready block
$('#email_address').blur(function(){

        var emailAddress = $('#email_address').val().split('@');
        var tagMap = {};
        var i = null;
        //See here its without var
        domain = emailAddress[1];
        for (i = 0; collectedDomains.length > i; i += 1) {
            var mydomain = collectedDomains[i].email_domain;               
        }

        var hasTag = function(tagName) {
            return tagMap[tagName];
        };  
   });
    $('#Button1').click(function(){
        //need the value of var mydomain available here
    });
});

答案 2 :(得分:0)

只需将其作为变量放在范围内的某个位置:

$('#email_address').blur(function(){

        var emailAddress = $('#email_address').val().split('@'),
            domain = emailAddress[1],
            tagMap = {},
            i = null,
            mydomain; //VIOLA!

        for (i = 0; collectedDomains.length > i; i += 1) {
            mydomain = collectedDomains[i].email_domain;               
        }

        var hasTag = function(tagName) {
            return tagMap[tagName];
        };  

        $('#Button1').click(function(){
            //need the value of var mydomain available here
        });
});