简体   繁体   English

如何访问HTML标记内的JavaScript变量

[英]How to access the javascript variable inside html tags

I wanted to added javascript variable inside html code. 我想在html代码中添加javascript变量。 Here is my code: 这是我的代码:

 <select id="currentrun" name="currentrun" >
        <option value=""><script>selectedrun</script></option>
 </select>

and my js function 和我的js功能

 var currentrun="";
 var selectedrun="";
  function setCurrentRun()
  { 
    currentrun = document.getElementById("runlist");
    selectedrun = currentrun.options[currentrun.selectedIndex].value;       
   }

But this doesn't work. 但这是行不通的。

Can anyone help me to do this. 谁能帮我做到这一点。

Thanks in advance. 提前致谢。

You don't have to run the script like that. 您不必像那样运行脚本。

The value of the currentrun can be retrieved as: 可以通过以下方式检索currentrun的值:

document.getElementById('currentrun').value

And for completeness, if you want to trigger a JavaScript function call each time the selection is modified, do this: 为了完整起见,如果您想在每次修改选择时触发JavaScript函数调用,请执行以下操作:

<select onchange="my_function();">
  <option>...</option>
</select>

It seems like you are trying to set the text of the option element with javascript. 似乎您正在尝试使用javascript设置option元素的文本。 Here is one way you can do it using the id of the element to get it and then set the text property of the element to your javascript variable: 这是一种使用元素id来获取它,然后将元素的text属性设置为javascript变量的方法:

<select id="currentrun" name="currentrun" >
    <option id="currentoption" value=""></option>
</select>

<script>
    document.getElementById("currentoption").text = selectedrun;     
</script>

Be sure to put any necessary javascript that declares and sets the selectedrun variable before the above script. 确保在上述脚本之前放置任何声明和设置selectedrun变量的必要javascript。

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

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