使用jQuery附加和调用动态javascript函数 [英] Append and call dynamic javascript function with jQuery
问题描述
您可以创建动态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屋!