【问题标题】:Chaining not working on jQuery Plugin链接在 jQuery 插件上不起作用
【发布时间】:2015-03-02 17:21:29
【问题描述】:

我正在编写一个插件来从我的公司内部 API 中提取列表,并且一切正常,但由于某种原因它不允许我链接其他方法。

(function( $ ) {

    $.fn.addListings = function(options){
        var defaults = {
            listingCount: 25,
            pageNumber: 1,
            customTemp: "<div class='listing'>\
            <img src='${IDXPhotoRef}'/>\
            <div class='address'>${Address}</div>\
            <div class='beds'> Beds: ${BedRooms}</div>\
            <div class='baths'>Baths: ${BathRooms}</div>\
            <div class='price'>Price: $${PriceFormatted}</div>\
            </div>",
            after: function(){}
        }

        var settings = $.extend({}, defaults, options );

        $.ajax({
          type: 'GET',
          // url: '/api/listings/?featuredlistings=1&pagesize=' + settings.listingCount + '&pagenumber=' + settings.pageNumber + '',
          url:'data.json',
          contentType: 'text/plain',
          crossDomain: true,
          context: $(this)
          })
        .done(function(data) {
            $.template("customTemp", settings.customTemp);
            var arrData = $.map(data[0], function(el) { return el; });
            for(i=0; i<arrData.length; i++){
                $.tmpl("customTemp", arrData[i]).appendTo(this);
            }

          })
        .always(function(){
            settings.after();
          });

    };

    return this;

    }( jQuery ));

https://github.com/cjthedizzy/jquery.addListingsJS/blob/master/jquery.addListings.js

【问题讨论】:

  • 这是它在控制台中吐出的错误 Uncaught TypeError: Cannot read property 'addClass' of undefined

标签: jquery jquery-plugins method-chaining


【解决方案1】:

return this 需要放在$.fn.addListings 块内:

(function($) {
    $.fn.addListings = function(options){
        // var defaults = {
        // ... rest of the code...

        return this;
    };
}(jQuery));

【讨论】:

  • 这很尴尬。谢谢,有时你在星期一只需要第二双眼睛。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2013-09-18
相关资源
最近更新 更多