使用javascript动态添加html变量
Adding html variables dynamically with javascript
我想根据用户选择的数字添加html变量:"<script>var var1 = new CalendarPopup();</script>
"。目前,我有一个ajax设置,它假设通过更改内部html来更改标记以添加变量,如下所示:
<div id="calVar">
<script>
var cal1 = new CalendarPopup();
var cal2 = new CalendarPopup();
</script>
</div>
function addRespDropDownAjax(currentNumberOfDropDown)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//Ajax receiving the response in this function
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
alert(document.getElementById('calVar').innerHTML);
}
};
//Send the Ajax request.
xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
xmlhttp.send();
}
最后一个警报:document.getElementById('calVar').inerHTML不返回任何内容,我的变量也没有创建。有什么想法吗?
非常感谢!!
HTML没有变量,在<script>
中定义的任何没有更深嵌套范围的变量都可以在window
对象外简单定义。
不要尝试插入HTML,只需使用:
window.cal3 = new CalendarPopup();
那么任何其他脚本现在或以后都可以访问该变量。
相关文章:
- 将html变量从Ajax传递到PHP
- 在JavaScript中使用HTML变量
- AngularJs - 从编译的 HTML/变量中获取一个字符串
- Node.js Express:重新访问注入到文件中.html变量
- PHP/HTML:将HTML变量保存在PHP会话变量中
- 如何从Ember.TextField的视图中切换HTML变量的值
- 使HTML变量可用于Rails渲染中的JavaScript
- 通过jquery从html变量中获取特定的标记
- 循环HTML变量并将span替换为content
- html变量到同一页面中的php变量
- 将HTML变量传递给Javascript
- 运行时在php HTML变量上运行javascript
- 在HTML变量中改变元素
- Javascript HTML变量表单入口
- 将Jquery/html变量链接到javascript
- Javascript/HTML变量未定义(全局变量)
- 将HTML变量传入Jquery
- 在JavaScript中使用HTML变量
- 使用javascript动态添加html变量
- JavaScript/HTML变量出现问题