我是一名 CoffeeScript 和 JavaScript 新手。
这里使用的是一个空白的 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>
再简单不过了,对吧?现在是表单的 View :
<%= 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 list 文件中的非注释:
//= require jquery
//= require jquery_ujs
//= require tkh_editor/tkh_editor
在 tkh_editor.js.coffee 文件中,如果我只是放置此代码,它就可以正常工作:
jQuery ->
$(".tkh-editable").css("border","solid 5px red")
它使用上面的类在我的文本区域字段周围添加了边框。
我正在尝试创建一个插件,但卡在了第 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'
请帮助并解释我做错了什么。
最佳答案
您可能只需要将 this
包装在 jQuery 中。尝试替换:
this.css("border","solid 5px red")
与:
$(this).css("border","solid 5px red")
关于javascript - HTML 对象与 jQuery 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13251321/