我使用slick js作为图像的滑块视图.

这是我的密码.

<div class="slider_wrap add-remove">
    <%= f.fields_for :images do |image_form| %>
      <%#= render 'images_fields', :f => image_form %>
        <div>
          <%= image_tag image_form.object.picture.url,:class=>"drop_down_link even img_prev" %>
        </div>
        <div class="image_upload_div">
          <div class="image-upload">
            <label>
              <i class="fa fa-cloud-upload">
                <%= image_form.file_field :picture ,:'data-role'=>"none",:onchange=>"readURL(this);" , :accept => 'image/jpeg , image/png' %>
              </i>
            </label>
          </div>
        </div>
    <% end %>
    <%= f.link_to_add "Add a picture", :images ,:id=>"add_pic" ,:class=>"js-add-slide", :style=>"display: none;"%>
</div>

<script>
function silder(){
    slideIndex = 0;
      $('.add-remove').slick({
        slidesToShow: 2,
        slidesToScroll: 2
      });
      $('.js-add-slide').on('click', function() {
        $('.add-remove').slick('slickAdd');
      });

      $('.js-remove-slide').on('click', function() {
        $('.add-remove').slick('slickRemove');
      });
});
function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
    $('.img_prev').last()
      .attr('src', e.target.result)
    };

    reader.readAsDataURL(input.files[0]);

    setTimeout(function(){
      $('#add_pic').trigger('click');
      silder();
    }, 100);
  }
}
</script>

现在,有了这段代码,我可以使用滑块了,但这并不正确,我遇到了错误:

未捕获的TypeError:无法读取null的属性"add"

推荐答案

这是由于calling init twice.这样做不会出错:

$(".slider").not('.slick-initialized').slick()

而且,"silder"看起来像一个拼写错误.

依赖超时也容易出错.不幸的是,有许多库可以避免Internet Explorer uses a different event to tell you when the HTML elements and JS libraries have been loaded.行左右的跨浏览器代码,但流行且相对较小的jQuery解决了如下计时问题:

$(function() {
  // Handler for .ready() called. Put the Slick Slider etc. init code here.
})

Ruby-on-rails相关问答推荐

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

Rails版本7.1.2:当验证失败且控制器发送422状态时,JS停止工作

尽管安装并需要 pry-rails gem,但 Rails 容器内出现未定义方法‘pry’错误

如何从设计中删除/禁用注册

Rails 将字符串与视图中的变量连接的最佳方法

如何从 Ruby on Rails 应用程序返回正确的 HTTP 错误代码

Rails 3 - Select 包含?

我如何在不同的视图中使用助手

Ruby - ActiveRecord::ConnectionNotEstablished

从子类中的重载方法调用基类方法

Rails如何对列求和?

在 Ruby on Rails 中循环对象属性

Active Record has_many:通过删除一条关联记录

Sidekiq 在 docker-compose 上的 127.0.0.1:6379 (Errno::ECONNREFUSED) 上连接到 Redis 时出错

如何在 Rails 应用程序中测试 ElasticSearch (Rspec)

为什么 Google Oauth 在我的 Rails 应用程序中返回无效的 redirect_urI?

如何创建迁移以仅在索引存在时删除索引,而不是在不存在时抛出异常?

扩展 Devise SessionsController 以使用 JSON 进行身份验证

按照给定 ID 数组的顺序按 ID 查找模型记录

如何删除特殊字符?