JavaScript global variable

Discutii si intrebari legate de scripturi si functii JavaScript, jQuery si Ajax, cod JavaScript in general.
liviumoc
Mesaje: 1

JavaScript global variable

buna
sunt incepator in js.inteleg diferenta intre js- client php- server.
vreau ca o variabila dintr-o functie sa devina o variabila grobala (pentru tot fisierul html daca am inteles eu bine).
mai exact vreau ca sa selectez un buton radio si rezultatul sa apara intr-un checkbox in value.

studiu de caz:

Cod: Selectaţi tot

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>

<body>
	<h2>Testing radio functionality</h2>
<script type="text/javascript">var radioArray=[null];</script>
<input name="juju" value="button1" type="radio" onclick="radioChange('juju','x',radioArray);" />BONT (O)
<input name="juju" value="button2" type="radio" onclick="radioChange('juju','o',radioArray);" />INTERM (X)
<input name="juju" value="button3" type="radio" onclick="radioChange('juju','I',radioArray);" />IMPLANT (I)
<br />

<script type="text/javascript">
function radioChange(radioSet,radioButton,radioArray)
  {
  //if(radioArray instanceof Array) {alert('Array Passed');}
  var oldButton=radioArray[0];
  if(radioArray[0] == null)
    {
   // alert('Old button was not defined');
    radioArray[0]=radioButton;
    }
  else
    {
    //alert('Old button was set to ' + oldButton);
    radioArray[0]=radioButton;
    }
  //alert('New button is set to ' + radioArray[0]);
	   vck =radioArray[0];
	  alert(vck);
  }
</script>
	<br>
	<input name="d11" type="checkbox" id="d11" title="d11" value="x">d11
	<input name="d12" type="checkbox" id="d11" title="d12" value="x">d12
	<hr>
	<script>
	document.write('input name="d11" type="checkbox" id="d11" title="d11" value="'+cvk+'">'+vck)
	</script>
</body>
</html>

MarPlo
Salut,
In JavaScript variabilele definite cu declaratia var in afara functiei sunt variabile globale, pot fi folosite si modificate in tot scriptul, inclusiv in functii.
Exemplu:

Cod: Selectaţi tot

var nr =3;

function testnr(n){
  alert(nr);  //3
  nr = n*2;
}

testnr(8);
alert(nr);  //16
- Vezi si lectia de pe site de la: marplo.net/javascript/definire-variabile-constante

Subiecte similare