如何获得一个就绪函数和另一个函数在 document.ready 中很好地播放

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

本文关键字:函数 ready document 很好 播放 另一个 一个 就绪 何获得      更新时间:2023-09-26

在我的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不切换(例如,当您转到其他页面并返回主按钮所在的主页面时......它不会切换。我必须在它再次开始工作之前刷新页面......我怀疑这与涡轮链接有关)...但这是一个次要问题。这不是这里的核心问题。

我也有这个:

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()返回未定义,如果#post_body不存在或它不是具有.val()方法的表单对象,则可能会发生这种情况。我认为我们必须查看您的 HTML 才能进一步提出建议,但似乎#post_body不存在。