Concatenated Variable Name in JavaScript
This problem is not as straightforward as I thought, I am trying to define the name of the variable as a mixture of report
and the actual value of the variable numClicks
.
report1, report2, report3, report4, etc...
<?
<script>
var numClicks = 0
</script>
echo "<img height =\"16\" src = \"images/stapler.png\"
onclick=\"
numClicks++;
var report+numClicks = '".$reports[$i]."';
return confirm(report+numClicks);
\">
"
?>
Is it possible to declare and define a variable like this in JavaScript, or d开发者_如何学运维o they have to be predefined before the page is loaded?
$reports[$i]
is a variable whose value is the name of the report.
What I would like to do is to enable the user to batch several reports together, then send that information to MySQL.
If report
is an object you can do:
var report = {};
report['click'+ numClicks] = 'somestuff';
console.log(report.click1); // logs 'somestuff'
You cannot do it this way. Perhaps if you show us more what you're really trying to accomplish, we can help you figure out how to do it.
Local variable names must be known at the time you write the code:
var myVariableName;
myVariableName
is an identifier, not a javascript expression.
You can create global variables from an expression because global variables are really just properties of the window object. So, you could declare a global variable like this:
window["report"+numClicks] = "foo";
You can also create arrays or objects of your own and assign values in the array or properties on the object using an expression as the key or index.
var reportArray = []; // declare array
reportArray[numClicks] = "foo"; // assign array entry
Or, you could use an object:
var reports = {};
reports[numClicks] = "foo"; // assign object property
In your particular code example, I don't quite follow what you're trying to do (I don't read PHP very well if that's what this is). But, I think it could all be changed to:
onclick="return(confirm('".$reports[$i]."'))"
or something like that (you might have to fix the server-side part of it). You don't need any local variables to do that.
this is a cleaner way of passing variables between php and javascript
settings.php
<?php
var settings = new array(
"name" => "foo",
"age" => "bar",
);
$json = json_encode(settings);
echo "var global_settings ={$json};"
?>
html/js
<script type="text/javascript" src="settings.php"></script>
<script type="text/javascript">
alert(global_settings.name);
alert(global_settings.age);
</script>
精彩评论