如何获得一个就绪函数和另一个函数在 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
不切换(例如,当您转到其他页面并返回主按钮所在的主页面时......它不会切换。我必须在它再次开始工作之前刷新页面......我怀疑这与涡轮链接有关)...但这是一个次要问题。这不是这里的核心问题。
我也有这个:
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
不存在。
相关文章:
- jQuery加载的async和ready函数不工作
- 如何通过documents.ready函数中的javascript自动按键(ctrl+shift+i)
- 停止对document.ready函数的重定向/刷新
- ready函数在每个页面中触发
- 函数从$(document).ready外部调用在$(document).ready中定义的函数
- 如果没有document.ready(),我怎么能拥有多个javascript函数呢
- 重载像$(document).ready这样的函数是错误的
- $(document)中的多个javascript函数.ready不工作
- JavaScript执行从函数声明开始,而不是从$(document).ready()开始
- 编写没有加载和.ready函数的JavaScript
- 在 $( 文档 ).ready 函数中使用字符串名称调用 javascript 函数
- 调用 Document.ready 外部的 AJAX 函数
- 在CrossRider内部创建的全局变量's的appAPI.ready()函数对页面不可用
- jQuery的事件处理程序运行良好,但应该't,因为它's不在ready()函数中
- 函数在例如$(document).ready()上注册时的通知
- 如何在document.ready(function)时运行隐藏函数和动画
- 超越了在document.ready()中编写简单函数
- Javascript on click事件在函数中不起作用,但在document.ready()中起作用
- 为什么document.ready中的事件处理程序函数有效但无效;取出后不起作用
- 如何调用函数ready()中的函数