Append and call dynamic javascript function with jQuery

半世苍凉 提交于 2020-01-06 08:57:11

问题


Can you create a dynamic javascript function and immediately call it?

I already found that you can't use the callback from append.

proposed, non working, code:

<script type="text/javascript">
var count=1;
$(document).ready(function(){
    $(".main").append('
       <script type="text/javascript">function init'+count+'(){alert("'+count+'");}<'+'/script>
    ');
    window['init'+count]();
});
</script>
<div class="main"></div>

Edit:

Narrowed it down to a synchronization problem. Placing alert("") between append and window makes it work, but that is not really a useful fix because the count might go up to a 100 when I place this code in a loop. Guess I'll have to keep looking.


回答1:


That should work, but you aren't quoting correctly. There shouldn't be any unescaped double quotes within append(" and "). Try:

$(".main").append("
       <script type=\"text/javascript\">function init'+count+'(){alert(\"'+count+'\");}<'+'/script>"
    );



回答2:


use an external script and $.getScript(), it allows you to specify a callback and makes your code a bit neater

$.getScript("http://scriptURL.com/script.js", function(){ itit(); });

Theres no point of inlining the code.. you could just run it in the same place you're appending the tags or use jQuery.globalEval();




回答3:


Yes, you can! This is the way javascript was invented! It is extremely powerful:

<script type="text/javascript">
var count=1;
var init = [];
$(document).ready(function(){
    (function (count) {
        init[count] = function () {
            alert(count);
        }
    })(count);
    init[count]();
});
</script>
<div class="main"></div>

or, if you just want to construct and call the function without storing it ...

<script type="text/javascript">
var count=1;
$(document).ready(function(){
    (function () {
        alert(count);
    })();
});
</script>
<div class="main"></div>


来源:https://stackoverflow.com/questions/7017241/append-and-call-dynamic-javascript-function-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!