---
title: "在Master页中使用jQuery"
author: "forestkqq"
date: "2011-05-11T08:30:00Z"
tags: ["JavaScript", "jQuery", "脚本"]
categories: ["编程语言"]
slug: "master-jquery"
draft: false
lastmod: "2011-05-11T08:30:00Z"
id: 1039573
url: "https://forestkqq.iteye.com/blog/1039573"
---

在普通页面中使用 jQuery，只需要在页面头部加入脚本文件即可，如：

 

```
<script src="Scripts/jquery-1.5.2.min.js" type="text/javascript" ></script>
```

 

但在 master文件中，直接这样使用却会遇到几个问题。

 

首先是会遇到路径问题。一般的解决办法是这样写：

```
<script type="text/javascript" src="<%=Page.ResolveUrl("~/jQueryScripts/jquery.js")%>"></script> 
```

 

但非常抱歉，我遇到了这样的错误：控件包含代码块(即 &lt;% ... %&gt;)，因此无法修改控件集合 ......

 

文章 [The Controls Collection Cannot Be Modified Because the Control Contains Code Blocks](http://leedumond.com/blog/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks/) 很好的解决了这个问题，它使用表达式数据绑定代替代码块。

 

 

下面是较完整的代码：

 

```
<head runat="server">
    <script type="text/javascript" src='<%# ResolveUrl("~/Scripts/jquery-1.5.2.min.js") %>'></script>
    ......    
    <script type="text/javascript">
        $(document).ready(function() {  
          ......
        });      // $(document).ready
    </script>
    ......
 </head>
```

 

在代码文件中：

```
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Header.DataBind(); // 表达式数据绑定
    }
```