【问题标题】:small jquery extension doesnt work小 jquery 扩展不起作用
【发布时间】:2016-09-13 09:00:07
【问题描述】:

在尝试了几种方法(第一次)为 jQuery 创建扩展之后......但它还不起作用:

(function($){ 
$.fn.fixInputWidthsForBlog = function() 
{ 
console.log('hi extension');
// var w = $('#newblogentryform input[name="headline"]').outerWidth();
// $('#newblogentryform textarea[name="text"]').outerWidth(w); 
// $('#newblogentryform submit[name="submit"]').outerWidth(w); 
}; // endFUNC
}(jQuery)); 

这(以下)是我得到错误的地方:

"jquery-3.1.0.min.js:2 Uncaught TypeError: $.fixInputWidthsForBlog is not a function"

$(document).ready(function(){

    $.fixInputWidthsForBlog(); 
    alert('ok1'); 
    $(window).on('resize', function(){ $.fixInputWidthsForBlog(); });
    $('.linkNewBlogEntry').on('click',function() { 
        $('#newblogentryformdiv').slideToggle().delay(1200).fixInputWidthsForBlog(); 
        // setTimeout("fixInputWidthsForBlog();",1200); 
        return false;   
        }); 
}); 

我也试过了:

$.fn.extend({
    fixInputWidthsForBlog = function() {} 
}); 

简单地说:

$.fn.fixInputWidthsForBlog = function() {}; 

但所有这些都会导致同样的错误:

"jquery-3.1.0.min.js:2 Uncaught TypeError: $.fixInputWidthsForBlog is not a function"

在我尝试执行的行中:

$.fixInputWidthsForBlog();  

以一种或另一种方式。

【问题讨论】:

  • 你真的是想在 jQuery 集 ($.fixInputWidthsForBlog();) 上而不是在 jQuery 集 ($(...).fixInputWidthsForBlog();) 上调用这个 not 吗?
  • thx @eisbehr: 我试过几次编辑,我还是新手 :)
  • @Crowder :是的,我想链接(第二个选项) - 并且还不太了解其中的区别,... :(
  • eisbehr's answer 应该很有用(看看它的onElements 部分)。我还编写了插件示例 herehere,FWIW。

标签: jquery


【解决方案1】:

扩展$.fn 仅适用于元素链,不适用于jQuery 对象的自身功能。为此,您需要直接扩展$,而不是fn

(function($) {
    // jQuery plugin
    $.fn.onElements = function() {
        console.log('hi, element chain plugin');

        // make chainable
        return this;
    };

    // jQuery object extension
    $.onjQuery = function() {
        console.log('hi, jQuery object extension');
    };
}(jQuery));

// will work
$('someElementSelector').onElements();
$('someElementSelector').onElements().onElements();
$.onjQuery();

// will not work
// $('someElementSelector').onjQuery();
// $.onElements();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 嗯,...所以我得到了最后一个问题:(如何)可以对两者使用相同的功能吗? ...但是考虑一下,我想这不是必需的,因为我可以为我需要的每种情况找到 onElements 解决方案。太感谢了! :)
  • 一般来说:$.fn.myPlugin = $.myPlugin = function() {};。但是你需要实现所有兼容的东西。有时这有点棘手。 ;) @davidman77
  • 非常酷!我曾经“想象”过那样的东西,thanx!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2023-03-11
  • 1970-01-01
  • 2013-12-28
相关资源
最近更新 更多