将页面加载到.keyup上时执行JQuery函数

时间:2018-08-22 08:40:01

标签: javascript jquery onload

我有一个看起来像这样的函数

var text_max = 200;
$('#count_message').html('0 / ' + text_max );

$('#text').keyup(function() {
  var text_length = $('#text').val().length;
  var text_remaining = text_max - text_length;

  $('#count_message').html(text_length + ' / ' + text_max);
});

我要实现的目标是在页面加载后立即执行,这意味着它计算的是文本区域中已经存在的文本的文本长度,而不是在您键入内容后才计算。

我尝试将其放在这样的函数中

function myFunction() {

var text_max = 200;
$('#count_message').html('0 / ' + text_max );

$('#text').keyup(function() {
  var text_length = $('#text').val().length;
  var text_remaining = text_max - text_length;

  $('#count_message').html(text_length + ' / ' + text_max);
});

}

然后像这样在体内执行它

<body onload="myFunction()">

但是我做的事情不正确,或者也许这不是做到这一点的方法。 我怀疑我必须在.keyup(function()内做一些事情,而不仅仅是将其加载到正文中,但不确定要做什么。我试图在jQuery事件方法中找到可以使用的东西,但是找不到任何有效的方法。另外,尝试了一些我在这里找到的想法,但也没有成功。

这是我从https://www.codeply.com/go/s0F9Iz38yn/bootstrap-textarea-with-character-count-_-bootstrap-3那里获得原始脚本的地方

编辑 我想保留.keyup功能,但也要计算页面加载的时间

4 个答案:

答案 0 :(得分:2)

从函数外部删除keyup并在加载时调用它,

var text_max = 200;
function myFunction($txt) {
   var text_length = $txt.val().length;
   var text_remaining = text_max - text_length;
   $('#count_message').html(text_length + ' / ' + text_max);    
}
$(function(){
   $('#text').keyup(function(){
       myFunction($(this));
   });
   myFunction($('#text'));
});

答案 1 :(得分:1)

您需要命名函数,以便您可以对其进行引用:

let text_max = 200,
    text_length,
    text_remaining,
    getTextLength = function() {
      text_length = $('#text').val().length;
      text_remaining = text_max - text_length;
      $('#count_message').html(text_length + ' / ' + text_max);
    }


/* 
 * now you can bind the function to any event:
 */

$(document).on('ready', function(){
  $('#text').on('keyup', getTextLength);
  $(window).on('load', getTextLength);
})
#text {
  min-height: 123px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="text">As you can see, function runs once on window.load and once on each #text.keyup

Type anything...</textarea>
<span id="count_message"></span>

请注意,我在解析脚本时不应用绑定,而是在document.ready上应用(当DOM解析器到达</html>时)。这样,我确保#text绑定到DOM后就存在。如果脚本在DOM中放置在#text之前,则接受的答案将失败,因为它执行得太早。

答案 2 :(得分:0)

如果“加载页面”是指加载HTML文档时,请尝试以下操作:

$(document).ready(function() {

});

如果“页面加载”是指页面上的所有图像也都已加载,请尝试以下操作:

$(window).load(function() {

});

答案 3 :(得分:0)

只需在window.onload函数中调用您的函数:

//call on page load
window.onload = function () {
myFunction()
}

//call on keyup
$('#text').keyup(function () {
myFunction()
});

function myFunction() {
var text_max = 200;
$('#count_message').html('0 / ' + text_max );
var text_length = $('#text').val().length;
var text_remaining = text_max - text_length;

$('#count_message').html(text_length + ' / ' + text_max);
}

您可以继续为keyUp和onLoad调用相同的函数。

相关问题