简体   繁体   English

从一个函数调用变量到另一个

[英]Calling a variable from one function to another

I have a create person button, and some radio buttons where I can assign a gender to the person. 我有一个创建人按钮,还有一些单选按钮,可以在其中为该人分配性别。 Ie: Male or Female. 即:男性或女性。

$('#BtnCreatePerson').click(function(e)
{   
var sPersonGender = $("#gender input[type='radio']:checked").val();
}

What do I do if I need to call the variable in another function in an external js file and place it in an if statement. 如果需要在外部js文件的另一个函数中调用变量并将其放在if语句中,该怎么办。 Like 喜欢

if (gender == Male && gender == Female)
{
   do something
}

UPDATE: I still can't get it to work. 更新:我仍然无法正常工作。 I've created a JSFIDDLE . 我创建了一个JSFIDDLE It's a bit messy, i know. 我知道这有点混乱。

Generally you would store the value outside of the function, possibly as a property of an object you have created, or the window object. 通常,您会将值存储在函数外部,可能作为您创建的对象或window对象的属性存储。

Person = {};

$('#BtnCreatePerson').click(function(e) {   
   Person.gender = $("#gender input[type='radio']:checked").val();
});

And in your other file: 并在您的其他文件中:

if (Person) {
   if (Person.gender === "Male") {
       // some code...
   } 
}

Why Not? 为什么不?

if ($("#gender input[type='radio']:checked").val()== Male && 
$("#gender input[type='radio']:checked").val()== Female)
{
   do something
}

Also I think that's an OR, since they can't be both male AND female :p 我也认为这是一个OR,因为他们不能同时是男性和女性:p

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

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