Variable not sent to other function
I have a number of links, that when clicked on, passes a variable thru to another portion of the page.
Yet, for some reason, I can’t figure it out! What am I missing?
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
return myid;
}
</script>
</head>
<body>
<a href="#" OnClick="myFunction(123456);">Click Me</a><br />
<script type="text/java开发者_Python百科script">
document.write(myid);
</script>
</body>
You are getting a little mixed up here. Even though the function returns a value, it has nothing to return it to. Try this:
<head>
<script type="text/javascript">
function myFunction(a){
myid="Hi There!"+a;
document.getElementById("debug").innerHTML = myid;
}
</script>
</head>
<body>
<a href="#" OnClick="myFunction(123456);">Click Me</a><br />
<div id="debug"></div>
</body>
if you want to use it later you need to declare myid as a global variable. its scope is currently only within myFunction. also the document.write() function will only execute at runtime so you need to have another function the executes that with every click, or just combine the two.
When you click the link all that happens is that the myFunction() is called which returns the string. The line document.write(myid);
is not executed anymore so nothing is visible.
<script>
// This is global
var myid = ''
myfunc = function(a){
myid = "Hi There!" + a;
alert(myid);
}
test_global = function(){
alert(myid);
}
</script>
<a href="javascript:void(0);" onclick="myfunc(12345);">Set MYID</a>
<input type="button" onclick="test_global();" value="Test MYID" />
Here is a simple example of some similar stuff:
<a href="#" type="button" OnClick="myf=myfunc(1234);alert(myf)" value="clickme">clickme</a> or <a href="#" type="button" OnClick="myf=myfunc(1234);document.getElementById('other').value=myf;" value="clickme">ClickMeAlso</a>
<input id='other' type='text'/>
<script>
function myfunc(a) {
return a + " howdy";
};
</script>
You can see this in action here:http://jsfiddle.net/5Sbn2/
精彩评论