如何在HTML中显示javascript代码

时间:2015-01-18 06:43:55

标签: javascript jquery html

我想在不执行代码的情况下显示javascript在页面中使用的javascript代码。我已经使用了.getScript()方法,但它执行了脚本。

请告诉我如何在不执行的情况下获取javascript代码并嵌入到HTML中。

HTML

<html>
<head>
    <script src='iwanttoshow.js'></script>
</head>
<body>
    <div class="js-source"></div>
</html>

javascript文件

$.getScript("/iwanttoshow.js", function(data) {
    window.alert("loaded!");
    $(".js-source").html(data);
}

2 个答案:

答案 0 :(得分:1)

你可以试试jquery .get()方法:

示例:

$.get("iwanttoshow.js",function(data,status){
  alert("Data: " + data + "\nStatus: " + status);
},"html");

了解更多信息:

http://api.jquery.com/jquery.get/

http://www.w3schools.com/jquery/ajax_get.asp

答案 1 :(得分:1)

<html>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <div>
        <!--Block to embed the js content, use <pre> tag-->
        <pre id="code">
        </pre>
    </div>
    <script>
        //test.js is your own file name
        $("#code").load("test.js");
    </script>
</html>

Jquery加载功能允许您加载资源。

使用<pre>标记来显示javascript的内容。