你可以使用自定义html在页面上替换自己的JavaScript函数吗? [英] Can you make a javascript function replace itself on the page with custom html?
问题描述
我有一些JavaScript会在页面上创建某种小部件。我会把这段代码给客户,所以我希望他们必须做的很少。
我现在正在工作的最明显的解决方案看起来像这样:
< div id =divContent>< / div>
< script type =text / javascript>
MakeWidget('divContent');
< / script>
制作小部件基本上会查找divContent div并将其填充到我的小部件的html中。
有没有更好的方法来做到这一点?
你可以使用脚本标记中的Javascript替换一个脚本标记吗?
如果我可以将代码缩减到只有MakeWidget函数,它会替换它本身,并使用函数生成的html代替脚本标记。
编辑 - 我基本上想要在MakeWidget函数被调用的地方生成HTML 。
您可以使用脚本标记中的JavaScript替换脚本标记吗?
是的。当< script>
元素到达时,假定它不是 defer
或异步
脚本,它将成为目前页面中的最后一个脚本元素。所以你可以说,不管是内联还是外部脚本:
(function(){
var scripts = document.getElementsByTagName('script');
var script = scripts [scripts.length-1];
var div = document。 createElement('div');
div.innerHTML ='无论将要插入什么内容';
script.parentNode.insertBefore(div,script);
})();
< / script>
I have some javascript which will create some sort of widget on a page. I will be giving this snippet to clients so I want them to have to do very little.
The most obvious solution which I have work right now looks something like this:
<div id="divContent"></div>
<script type="text/javascript">
MakeWidget('divContent');
</script>
Make widget basically looks for the divContent div and fill it with my widget's html.
Is there a better way to do this? Can you replace a Script Tag with a Div using Javascript in that Script Tag?
I would really like it if I could reduce the code down to only the MakeWidget function and it would replace itself and the script tag with the html the function generates.
Edit - I essentially want to generate HTML exactly where the MakeWidget function is called on the page.
Can you replace a Script Tag with a Div using Javascript in that Script Tag?
Yes. When the <script>
element is reached, assuming it is not a defer
or async
script, it will be the last script element in the page so far. So you can say, either inline or in an external script:
<script type="text/javascript">
(function() {
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
var div= document.createElement('div');
div.innerHTML= 'Whatever content is going to be inserted';
script.parentNode.insertBefore(div, script);
})();
</script>
这篇关于你可以使用自定义html在页面上替换自己的JavaScript函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!