---
title: "用jQuery代替Rails的Prototype"
author: "taito"
date: "2010-07-21T14:13:58Z"
tags: []
categories: ["编程语言"]
slug: "jquery-rails-prototype"
draft: false
lastmod: "2010-07-21T14:16:27Z"
id: 717792
url: "https://taito.iteye.com/blog/717792"
---

默认的情况下，Rails是使用[Prototype](http://www.prototypejs.org/) 做为javascript 框架,如果我们想用 [jQuery](http://www.jquery.com/) 来替换它，可以用如下方法

 

先来看一些对比的例子, jQuery能更好的实现代码从表现层分离

 

**Prototype**

 

```
$('the-link').observe('click', function() {
  $('the-div').addClass('hello');
});
```

 **jQuery**

 

```
$('#the-link').click( function() {
  $('#the-div').addClass('hello');
});
```

 

更多的例子请看这个ppt

 

 

 

虽然我们可以使用jQuery的很多优秀的方法，不过我们又不想抛弃原来 prototype的众多 helper方法，怎么办呢。

安装jRails

 

把它做为plugins 装在你的项目里，你就可以正常使用你原有的 prototype的方法了。比如remote\_form等。

 

替换

```
<%= javascript_include_tag :defaults%>
```

 

为

```
<%= javascript_include_tag 'jquery'%>
<%= javascript_include_tag 'jquery-ui'%>
<%= javascript_include_tag 'jrails'%> 
```

 

在Rjs 也可以使用 jQuery, 如：

 

```
page << "$('span#bacon').text('CHunKy');"
```

 

 

自带的jquery-ui 你可以参考这个站点：[jQuery UI site](http://ui.jquery.com/)

 

 

====

Ref: [http://jimneath.org/2008/06/18/using-jquery-with-ruby-on-rails/](http://jimneath.org/2008/06/18/using-jquery-with-ruby-on-rails/)