Rails 7 jQuery:未介绍的参考文献:$未定义
通过以下内容添加了jQuery 7.0.2.4项目。
我 :
pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"
然后在app/javascript/application.js
中添加行以导入jQuery:
import '@hotwired/turbo-rails'
import 'controllers'
import 'bootstrap'
import jquery from 'jquery'
window.jQuery = jquery
window.$ = jquery
我使用JavaScript的视图:
<%= form_with(model: @micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class='field'>
<%= f.text_area :content, placeholder: 'Compose new micropost...' %>
</div>
<%= f.submit 'Post', class: 'btn btn-primary' %>
<span class='image'>
<%= f.file_field :image %>
</span>
<% end %>
<script type='text/javascript'>
$('#micropost_image').bind('change', function() {
if (this.files[0].size/1024/1024 > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.')
$('#micropost_image').val('')
}
})
</script>
当加载视图时,Chrome Console显示:
Uncaught ReferenceError: $ is not defined at (index):103:3
当我选择大于5MB的文件时,消息弹出,所以我认为脚本没有运行。
如何修复它?
I added jQuery to my Rails 7.0.2.4 project by the following:
First run command ./bin/importmap pin jquery
, to add the following line in config/importmap.rb
:
pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"
Then add lines to import jQuery in app/javascript/application.js
:
import '@hotwired/turbo-rails'
import 'controllers'
import 'bootstrap'
import jquery from 'jquery'
window.jQuery = jquery
window.$ = jquery
My view with javascript:
<%= form_with(model: @micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class='field'>
<%= f.text_area :content, placeholder: 'Compose new micropost...' %>
</div>
<%= f.submit 'Post', class: 'btn btn-primary' %>
<span class='image'>
<%= f.file_field :image %>
</span>
<% end %>
<script type='text/javascript'>
$('#micropost_image').bind('change', function() {
if (this.files[0].size/1024/1024 > 5) {
alert('Maximum file size is 5MB. Please choose a smaller file.')
$('#micropost_image').val('')
}
})
</script>
When the view is loaded, Chrome console shows:
Uncaught ReferenceError: $ is not defined at (index):103:3
And when I select a file bigger than 5MB, no error message is popped up, so I think the script isn't run.
How to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试以下操作:
try this: