【问题标题】:jquery plugin not applying the plugin code body to each matched elementjquery插件未将插件代码主体应用于每个匹配的元素
【发布时间】:2012-05-31 11:16:35
【问题描述】:

我正在制作我的第一个文件上传器 jquery 插件(在 coffeescript 中):

    $.fn.uploadable = (opts={}) ->
      console.log $(@).attr('type') # undefined
      event = if $(@).attr('type') is 'file' then 'change' else 'drop'
      @
      .on event, (evt) ->
        # do something
        off
      .on 'dragover', (evt) -> off


    $('#files_input, #drop_zone').uploadable

所以你可以看到,在第一个 .on() 中,我正在确定事件的元素是否是浏览文件按钮;如果是,那么当用户使用时,该元素将被监听“更改”事件选择文件,如果否,那么我假设它是一些普通的旧 div 或用于 HTML5 拖放操作的东西。

所以我在一个 INPUT 元素和一个 DIV 元素上使用插件。正如您从我的 console.log 中看到的那样,记录了“未定义”

到目前为止,我只知道像 attr() 这样的调用方法,您只能从列出的选择器元素之一中获得结果。但是我需要为每个匹配的元素单独设置 .on(event) 的事件变量。我该怎么做?

谢谢

【问题讨论】:

    标签: jquery jquery-plugins coffeescript


    【解决方案1】:

    通常的插件模式如下所示:

    $.fn.plugin = function(options) {
        options = $.extend({ }, $.fn.plugin.defaults, options || { });
        return this.each(function() {
            // Do things to $(this) to set up your plugin.
        });
    };
    $.fn.plugin.defaults = { ... };
    

    CoffeeScript 版本是:

    $.fn.plugin = (options = { }) ->
        options = $.extend({ }, $.fn.plugin.defaults, options)
        @.each ->
            # Do things to $(@) to set up your plugin
    $.fn.plugin.defaults = { ... }
    

    return this.eachreturn 部分为您提供通常的链接,this.each 部分允许插件一次绑定到多个东西。

    应用这个你的案例会给你:

    $.fn.uploadable = (opts = { }) ->
      @.each ->
        event = if $(@).attr('type') is 'file' then 'change' else 'drop'
        $(@)
          .on event, (evt) ->
            # do something
            off
          .on 'dragover', (evt) -> off
    

    【讨论】:

    • 我认为@.each 做到了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2011-04-15
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多