我是CoffeeScript和JavaScript的新手。HTML對象與jQuery對象
在這裏工作是一個空白的Rails 3.2.8應用程序。
這裏是直佈局代碼:
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
<%= javascript_include_tag "application" %>
</body>
</html>
得不能再簡單了吧?現在的形式觀點:
<%= form_for(@note) do |f| %>
<% if @note.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@note.errors.count, "error") %> prohibited this note from being saved:</h2>
<ul>
<% @note.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_area :body, class: 'tkh-editable' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
雖然研究這個話題,我看到很多程序員不得不使用jQuery加載兩次或以錯誤的順序問題。
以下是我的application.js非註釋清單文件:
//= require jquery
//= require jquery_ujs
//= require tkh_editor/tkh_editor
在tkh_editor.js.coffee文件,如果我只是把這個代碼,它工作得很好:
jQuery ->
$(".tkh-editable").css("border","solid 5px red")
它在我的textarea字段的上面添加了一個邊框。
我正在嘗試創建一個插件並將其卡在步驟1中。
爲什麼下面的代碼不工作?
jQuery.fn.extend
tkhEditor: ->
return @each ->
this.css("border","solid 5px red")
jQuery ->
$(".tkh-editable").tkhEditor()
中的Chrome控制檯使我有以下錯誤:
Uncaught TypeError: Object # has no method 'css'
請幫忙解釋一下我做錯了什麼。
實際上,根據jquery的編寫指南http://docs.jquery.com/Plugins/Authoring一旦做對了,你的插件代碼中的'this'應該已經包裝在jQuery中了,所以你不必做大衛在他的答案中建議。問題在於,如何在coffescript中體現這一點。 – WTK
應發佈發送到頁面 – charlietfl
的結果源代碼@WTK這是需要封裝的'.each'回調中的'this'上下文。 – David