如何命名和重用 javascript 函数

How to name and reuse a javascript function

本文关键字:javascript 函数 何命名      更新时间:2023-09-26

我有以下jQuery代码,我想通过从jQuery代码的其他部分调用它来重用它。我该怎么做?

$(document).ready(function() {              
    $('#share_mention').charcount({
        maxLength: 140,
        preventOverage: false
    });
    $('.countable').bind('update', function(evt, length, remaining) {
        var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;                 
    });
});

有很多方法可以给这只猫剥皮,但这里有一种方法。

var yourNameSpace = {};
yourNameSpace.YourFunction = function(){
   $('#share_mention').charcount({
   maxLength: 140,
   preventOverage: false
  });
  $('.countable').bind('update', function(evt, length, remaining) {
  var message = 'id=' + $(evt.target).attr('id') + ', length=' + length + ', remaining=' + remaining;                 
  });
}
$(document).ready(function() {   
  yourNameSpace.YourFunction()
});

首先,没有jQuery函数这样的东西。这是一个JavaScript函数。该事件隐式传递给回调函数。

function countCats (event) {}
$('.cats').on('click', countCats);