我是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