Javascript函数仅适用于页面,而不适用于文件

时间:2013-07-10 19:46:56

标签: jquery asp.net-mvc

您好!

我在extern js文件中声明了函数:

$(function () {
        $('[data-provide=typeahead]').each(function () {
            var self = $(this);
            self.typeahead({
                source: function (term, process) {
                    var url = self.data('url');
                    console.log(url);

                    return $.getJSON(url, { term: term }, function (data) {
                        return process(data);
                    });
                }
            });
        });
    });

但它不起作用。执行该功能后,它不会继续绕过内容。

Extern file

在部分母版页上讲述链接:

...
<script src="~/Scripts/Login.js?v.3.0"></script>
... 
<div class="container">
        @RenderBody()
</div>
...

只有当我将此代码直接放在页面上时才开始工作。

on page

有什么问题?

谢谢!

3 个答案:

答案 0 :(得分:3)

哟不能在客户端使用~,这是一项ASP专用功能,仅在您使用<script runat="server">时才有效

<script src="~/Scripts/Login.js?v.3.0"></script>

你很可能会给它错误的道路。查看您的网络选项卡,确保该脚本的请求有效

尝试

<script src="/Scripts/Login.js?v.3.0"></script>

请参阅slash(/) vs tilde slash (~/) in style sheet path in asp.net

答案 1 :(得分:0)

我解决了这个问题。同样,胡安门德斯是对的。问题在于链接到脚本文件。代替 <script src ....>...</script>

我正在创建bundling

1)在App_Start文件夹中创建文件BundleConfig.cs,代码如下:

public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-*"));

            bundles.Add(new ScriptBundle("~/bundles/login").Include(
                        "~/Scripts/Login.js"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrapJS").Include(
                        "~/Scripts/bootstrap*"));

            bundles.Add(new StyleBundle("~/bundles/ProfitStyle")
                            .Include("~/Content/ProfitStyle.css"));

            bundles.Add(new StyleBundle("~/bundles/bootstrapCSS")
                            .Include("~/Content/bootstrap*"));
        }
    }

这里我们在内容文件上注册了捆绑包。

2)在Global.asax中创建init bundle,添加代码行:

BundleConfig.RegisterBundles(BundleTable.Bundles);

3)刚刚添加了我们需要的文件的链接:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/login")
@Scripts.Render("~/bundles/bootstrap")
@Styles.Render("~/bundles/bootstrapCSS")
@Styles.Render("~/bundles/ProfitStyle")

SORRY,JUAN

答案 2 :(得分:0)

而且,正如其他情况只是在视图页面中写下这段代码:

<script src="@Url.Content("~/Scripts/Login.js?v.3.0")"></script>