RAILS 6 - 如何使用 EasyAutocomplete [英] RAILS 6 - how to use EasyAutocomplete

查看:30
本文介绍了RAILS 6 - 如何使用 EasyAutocomplete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在最后几个小时内尝试将 EasyAutocomplete 集成到 RAILS 6 中.但没那么容易.

I try the last hours to integrate EasyAutocomplete into RAILS 6. But not so easy.

我做了什么:

用yarn安装Javascript包:

Install Javascript Package with yarn:

# yarn add easy-autocomplete

在文件 app/javascript/packs/application.js 中添加这个

Add this in the file app/javascript/packs/application.js

import "easy-autocomplete"

在文件 app/assets/stylesheets/application.css 中添加这个

Add this in the file app/assets/stylesheets/application.css

*= require easy-autocomplete
*= require easy-autocomplete.themes

然后启动 Rails 服务器并刷新网页.然后尝试使用它.进入开发者控制台并输入:

Then start the Rails Server and refresh the Web Page. Then try to use it. Go into the developer console and type :

var options = {
data: ["otto", "hans", "paula"] 
};

$("#task_name_search_field").easyAutocomplete(options);

task_name_search_field 之前定义为 id :

task_name_search_field was previously defined as id :

<input type="search" class="form-control" id="task_name_search_field">

我收到了这条消息:类型错误:$(...).EasyAutocomplete 不是函数

I got this message: TypeError: $(...).EasyAutocomplete is not a function

有什么想法吗?

推荐答案

我遇到了同样的问题.Turbolinks 不给脚本访问权限,代码需要在加载后运行,类似这样:

I had the same problem. Turbolinks does not give access to the script, the code needs to be run after it is loaded, something like this:

document.addEventListener("turbolinks:load", function() {
  var options = {
   data: ["otto", "hans", "paula"] 
  };

  $("#task_name_search_field").easyAutocomplete(options);
});

为了使自动完成工作,您需要像这样向 application.js 添加一个脚本文件:

In order for the autocomplete to work, you need to add a script file to the application.js like this:

require("packs/youfile")

如果对你有帮助,这里是我的代码示例:

If it helps you, here is an example of my code:

document.addEventListener("turbolinks:load", function() {
 $input = $("[data-behavior='autocomplete']")

 var options = {
  getValue: "full_name",
  url: function(phrase) {
  return "/search.json?q=" + phrase;
 },
categories: [
  {
    listLocation: "cameras",
    header: "<strong>Cameras</strong>",
  }
],
list: {
  onChooseEvent: function() {
    var url = $input.getSelectedItemData().url
    $input.val("")
    Turbolinks.visit(url)
  }
 }
}
$input.easyAutocomplete(options)});

这篇关于RAILS 6 - 如何使用 EasyAutocomplete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆