简体   繁体   English

在脚本模板中运行javascript / jquery(脚本标记中的脚本)

[英]Run javascript/jquery inside a script template (script in a script tag)

I have a client side CMS div that gets loaded into script template. 我有一个客户端CMS div加载到脚本模板。 I need to run a script inside that div. 我需要在div中运行一个脚本。 How can I run myFunction inside this script tag? 如何在此脚本标记内运行myFunction? It's closing the first script tag early :( 它正在关闭第一个脚本标签:(

 <script type="text/html" id="tmpl-foo">

 <div id="myCMSdiv">

 <p> My Content </p>

 <script>
 myFunction();
 </script>

 </div>

 </script>

Give a bit of context of how your CMS binds the template (the JS file) 给出一些关于CMS如何绑定模板的上下文(JS文件)
If your CMS uses template binding then you can just use afterRender . 如果您的CMS使用template绑定,那么您可以使用afterRender

Just like this: 像这样:

 var viewModel = function() { this.myFunction = function() { console.log("test"); } } ko.applyBindings(new viewModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <div data-bind="template: { name: 'tmpl-foo', afterRender: myFunction }"></div> <script type="text/html" id="tmpl-foo"> <div id="myCMSdiv"> <p>My Content</p> </div> </script> 

More info on template binding here . 关于更多信息template结合在这里

If your CMS uses it as a component though then you need another approach. 如果您的CMS将其用作component那么您需要另一种方法。
Check this post on how to do it but the gist is just the same as above. 查看这篇文章如何做,但要点与上面相同。

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

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