简体   繁体   中英

javascript/jquery passing variables

I was wondering if there is a way that I can pass variables like this:

<script type="text/javascript">
width = 300;
</script>

<script type="text/javascript">
(function(){
    var k = width;
    alert(k);
});
</script>

I'm trying to learn how I can pass width into the variable k. I dont want to do var width =300 Is there a way to do such a thing like this? so eventually I can place the bottom script, (function(){...}); into a file where I can just do this

<script type="text/javascript">
width = 300;

//more variables if needed

//height = 300;
//name = "example";
//...
</script>

<script type="text/javascript" src="thefile.js"></script>

So I can add more variables if I have to

Thanks!

<script type="text/javascript">
    window.$vars = {
        width: 300
    };
</script>

<script type="text/javascript">
    (function(){
        var k = window.$vars.width;
        alert(k);
    })();
</script>

Putting the variable in global scope will do it.

Yes You can do this.

If you declare a variable outside of any function or closure that will be a global variable(a property of window object) and you can use that variable anywhere(even in external js files) after that declaration.

But it's better to put all your global vars inside a object so it doesnt pollute the global namespace much like this

globalVars = {
   width: 300,
   height: 200
};

then use them like

(function(){
        var k = globalVars.width;
        alert(k);
    });

it looks like you are trying to create a large configuration setting file. i would create an object and reference it's properties for local variable assignment...

so i would do this:

<script type="text/javascript">
    var myLargeObject = {
          width:300,
          name:"give it a name",
          height:500,
          etc..
    }
</script>

//then reference your values like this...
<script type="text/javascript">
    (function(){
        var k = myLargeObject.width;
        alert(k);
    });
</script>

You could put in a file something like this

function getVariable(width)
{
  var newWidth = width;
  alert(newWidth);
  //do something else
  return newWidth
}

calling the function:

getVariable(300)

or

<a href='javascript:getVariable(300);'>something</a>

is this what you want to accomplish?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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