使用jQuery附加和调用动态javascript函数 [英] Append and call dynamic javascript function with jQuery

查看:74
本文介绍了使用jQuery附加和调用动态javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以创建动态javascript函数并立即调用它吗?

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

我已经发现您不能使用append中的回调.

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

建议的无效代码:

<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>

将其缩小到同步问题.在附录和窗口之间放置alert("")使其可以工作,但这并不是真正有用的解决方法,因为当我将此代码放入循环中时,计数可能会增加到100. 猜猜我必须继续寻找.

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.

推荐答案

这应该可以,但是您的引用不正确. append("")中不应有任何未转义的双引号.试试:

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>"
    );

这篇关于使用jQuery附加和调用动态javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆