简体   繁体   English

在运行时从innerHtml中添加并调用javascript函数

[英]Add and call javascript function at runtime from within innerHtml

I am using dotnet.highcharts to create a chart at runtime: 我正在使用dotnet.highcharts在运行时创建图表:

I use an ajax call an receive formatted html as a result. 结果,我使用ajax调用接收格式的html。 This is what I get back: 这就是我得到的:

<div id='bbb55283bfc3440a96c7ae26e130173f_container'></div><script type='text/javascript'>
var bbb55283bfc3440a96c7ae26e130173f;
function TestFunction() {
    bbb55283bfc3440a96c7ae26e130173f = new Highcharts.Chart({
        chart: { renderTo:'bbb55283bfc3440a96c7ae26e130173f_container', defaultSeriesType: 'line' }, 
        title: { text: 'Test' }, 
        xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] }, 
        series: [{ data: [12, 23, 1, 9, 34, 54] }]
    });
}
</script>

Now I am putting this inside a div element (where data is the above snippet): 现在,我将其放在div元素中(上面的代码是数据):

$(myDiv).innerHtml = data;

Next I need to call the function TestFunction() 接下来,我需要调用函数TestFunction()

How can I do that? 我怎样才能做到这一点? It lives inside myDiv like this: 它像这样生活在myDiv中:

<div id="chartContainer" style="float:left">
    <div id="bbb55283bfc3440a96c7ae26e130173f_container"></div>
    <script type="text/javascript">
      var bbb55283bfc3440a96c7ae26e130173f;
      function TestFunction() {
        bbb55283bfc3440a96c7ae26e130173f = new Highcharts.Chart({
            chart: { renderTo: 'bbb55283bfc3440a96c7ae26e130173f_container', defaultSeriesType: 'line' },
            title: { text: 'Test' },
            xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'] },
            series: [{ data: [12, 23, 1, 9, 34, 54] }]
            });
      }
    </script>

TestFunction doesn't "live inside the div ". TestFunction不“位于div内部”。 JavaScript isn't part of the markup in that manner. 以这种方式,JavaScript并不是标记的一部分。

As soon as the function is defined: 定义函数后:

function TestFunction() {
    // code
}

It is available from then on as a global function on the window object. 从那时起,它就可以作为window对象上的全局函数使用。 So from anywhere else on the page you can invoke it: 因此,您可以从页面上的其他任何地方调用它:

TestFunction();

Of course, if this div is repeated in any way and you're assuming some kind of namespacing of functions within div s, then you'll find that not to be the case in practice. 当然,如果以任何方式重复div ,并且您假设div的函数具有某种命名空间,那么实际上您会发现情况并非如此。 If the function is globally defined again anywhere in the document then that second definition will simply overwrite the first one. 如果在文档中的任何位置再次全局定义该函数,则该第二个定义将简单地覆盖第一个。

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

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