如何调试通过 AJAX(特别是 jQuery)加载的 Javascript [英] How do I debug Javascript which was loaded via AJAX (specifically jQuery)

查看:21
本文介绍了如何调试通过 AJAX(特别是 jQuery)加载的 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近改变了我的编码风格,使用更复杂的项目来按需"加载页面(及其嵌入式脚本).但是,很难像加载这些脚本时那样调试它们:

I have changed my coding style with more complex projects to loading pages (And their embedded scripts) "on demand" recently. However, it is difficult to debug those scripts as when they are loaded like:

jQuery.get('/myModularPage', function(html){ /* insert the loaded page into the DOM */ });

$('#some-container').load('/myOtherPage');

这些脚本运行完美,但如果我在调试,如何在这些动态加载的页面和脚本中设置断点?

These scripts run perfectly, but if I'm debugging, how can I set breakpoints in these dynamically loaded pages and scripts?

推荐答案

更新

接受的表单现在带有 #(井号)而不是 @(符号)

The accepted form is now with a # (hashtag) rather than @ (at symbol)

语法已更改以避免与 IE 条件编译语句冲突和其他一些问题(感谢 Oleksandr Pshenychnyy 和 Varunkumar Nagarajan 指出这一点)

The syntax was changed to to avoid conflicts with IE conditional compilation statements and some other issues (thanks to Oleksandr Pshenychnyy and Varunkumar Nagarajan for pointing this out)

//#sourceURL=/path/to/file 

这实际上可以是任何可以帮助您识别代码块的字符串.

This can really be any string that helps you identify the block of code.

JMac 的另一个优点:

An additional good point from JMac:

对我来说,js 文件显示在源列表中组称为(无域)".可能值得一提,因为我错过了一开始!

For me, the js file was being displayed in the sources list within a group called "(no domain)". Might be worth mentioning as I missed it at first!

原创

在遇到 这篇文章.它确实非常适合我的开发环境(我写这篇文章时是 Chrome 22).

I struggled with the above for about a week before running across this article. It really does work perfectly for my development environment (Chrome 22 as I write this).

Firebug 还支持开发人员命名的 eval() 缓冲区:只需在 eval(expression) 末尾添加一行,例如:

Firebug also supports developer-named eval() buffers: just add a line to the end of your eval(expression) like:

//@ sourceURL=foo.js

例如,给定这个简单的 html 文档:

For example, given this simple html document:

<!DOCTYPE html>
<html>
<body>
    <p>My page's content</p>
    <div id="counter"></div>
    <script type="text/javascript">
        //if this page is loaded into the DOM via ajax 
        //the following code can't be debugged 
        //(or even browsed in dev-tools)

        for(i=0;i<10;i+=1) {
            document.getElementById('counter').innerText = i;
        }

        //but if I add the line below
        //it will "magically" show up in Dev Tools (or Firebug)

        //@ sourceURL=/path/to/my/ajaxed/page
    </script>
<body>
</html>

我还没有发现的东西:

  • 是否必须为内联脚本的每个脚本块执行此操作?
  • 它必须是脚本块的最后一行吗?(这篇文章建议的答案是)

这篇关于如何调试通过 AJAX(特别是 jQuery)加载的 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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