我如何获得一个现成的功能和另一个在 document.ready 中很好地发挥作用的功能?

How do I get a ready function and another function to play nicely in document.ready?

在我的 post.js 中,我有这个:

var ready;
ready = function() {

    // This is the Sidebar toggle functionality
    var toggleSidebar = $(".togglesidebar");
    var primary = $("#primary");
    var secondary = $("#secondary");

    toggleSidebar.on("click", function(){

        if(primary.hasClass("col-sm-9")){
            primary.removeClass("col-sm-9");
            primary.addClass("col-sm-12");
            secondary.css('display', 'none');
        }
        else {
            primary.removeClass("col-sm-12");
            primary.addClass("col-sm-9");
            secondary.css('display', 'inline-block');
        }
    }); 
};

$(document).ready(ready);

大部分时间都有效。有时 toggleSidebar 不会切换(例如,当您转到另一个页面并返回主按钮所在的主页面时......它不会切换。我必须先刷新页面它又开始工作了……不过我怀疑这与 Turbolinks 有关)……但这是一个附带问题。这不是这里的核心问题。

我也有这个:

counter = function() {
    var body_value = $('#post_body').val();
    var title_value = $('#post_title').val();       

    if (body_value.length == 0) {
        $('#wordCountBody').html(0);
        return;
    }

    if (title_value.length == 0) {
        $('#wordCountTitle').html(0);
        return;
    }

    var regex = /\s+/gi;
    var wordCountBody = body_value.trim().replace(regex, ' ').split(' ').length;
    var wordCountTitle = title_value.trim().replace(regex, ' ').split(' ').length;

    $('#wordCountBody').html(wordCountBody);
    $('#wordCountTitle').html(wordCountTitle);
};

$(document).on('ready page:load', function () {
  $('#count').click(counter);
    $('#post_body, #post_title').on('change keydown keypress keyup blur focus', counter);
});

这根本不起作用。事实上,每当我将光标放在 JS 控制台的 #post_title 文本字段中时,我都会收到此错误:

Uncaught TypeError: Cannot read property 'length' of undefined

我怀疑与上述有关。

可能是什么原因造成的?

此外,我不确定 post.js 文件中这些语句的顺序是否真的重要,为了这个问题我更改了顺序 - 所以它更清楚。

然而,在我的实际post.js中,顺序是:

var ready;
ready function() declaration
counter function() declaration
$(document).ready(ready);
$(document).on('ready page:load', function () {
  $('#count').click(counter);
    $('#post_body, #post_title').on('change keydown keypress keyup blur focus', counter);
});

所有这些感觉都不对,我只是不知道如何将它们组合起来并清理掉。

想法?

然后,很明显 body_value 未定义,这是因为 $('#post_body').val() returns 未定义,如果 #post_body 不存在或如果它不是具有 .val() 方法的表单对象。我认为我们必须查看您的 HTML 才能进一步提供建议,但 #post_body 似乎不存在。