使用javascript动态添加html变量

Adding html variables dynamically with javascript

本文关键字:html 变量 添加 动态 javascript 使用      更新时间:2023-09-26

我想根据用户选择的数字添加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();

那么任何其他脚本现在或以后都可以访问该变量。