gpt4 book ai didi

javascript - 字数计数器 Javascript 函数调用

转载 作者:行者123 更新时间:2023-12-02 18:57:49 24 4
gpt4 key购买 nike

希望在网站上的输入文本框旁边有一个单词计数器

当用户单击或修改文本时可以显示计数,但我想在页面加载完成后立即加载。

$(document).ready(function() {

$("#product_name").change(displayText).keyup(displayText);

function displayText(){
$("em#counter").text($(this).val().length +' chars');
}
});

所以我尝试了下面的代码,但无法让它工作,也不知道为什么。

$(document).ready(function() {

if($("#product_name").length){
displayText();
}
$("#product_name").change(displayText).keyup(displayText);

function displayText(){
$("em#counter").text($(this).val().length +' chars');
}
});

非常感谢。

最佳答案

试试这个

if($("#product_name").length){
displayText();
}
$("#product_name").change(displayText).keyup(displayText);

function displayText(){
$("em#counter").text($("#product_name").val().length +' chars');
}

演示:Fiddle

问题出在页面加载期间的 displayText() 调用。在 displayText 中,您使用 $(this) 来访问输入字段,该字段用作事件处理程序。但是当你直接调用 displayText 时,this 将指向窗口对象。

关于javascript - 字数计数器 Javascript 函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15151836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com