Javascript 页面加载时Textarea字符计数失败
英语不是我的母语,所以我要为语法错误提前道歉 我使用javascript来计算textarea的字符数,代码工作平稳,在键入时显示字符限制减少,使用此代码我在textarea上调用了一个php方法,从数据库调用了一个文本,这就是问题所在,在加载时测试页面时,它会在文本区域显示文本,但字符限制保持在500,当然,如果u在文本区域中键入正确的字符限制,它会更改值 如何在页面加载时显示正确的字符限制 这是我的密码: HTML代码:Javascript 页面加载时Textarea字符计数失败,javascript,events,textarea,html,Javascript,Events,Textarea,Html,英语不是我的母语,所以我要为语法错误提前道歉 我使用javascript来计算textarea的字符数,代码工作平稳,在键入时显示字符限制减少,使用此代码我在textarea上调用了一个php方法,从数据库调用了一个文本,这就是问题所在,在加载时测试页面时,它会在文本区域显示文本,但字符限制保持在500,当然,如果u在文本区域中键入正确的字符限制,它会更改值 如何在页面加载时显示正确的字符限制 这是我的密码: HTML代码: <tr> <td align="center" co
<tr>
<td align="center" colspan="4">
<textarea "rows="10" cols="35" onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)"><?php echo $oRep->getDescripcion(); ?> </textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4"><p><strong><span id="charCount">500</span></strong> Caracteres disponibles.</p></td>
</tr>
var maxLength=500;
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) charCount.innerHTML = maxLength - el.value.length;
return true;
}
我试图在textarea上添加一个事件,如
onchange=“return charLimit(this)
,但没有任何更改。首先,我将为该textarea添加一个id,比如“descriptionTextArea”。
其次,我将监听body上的“onload”事件(例如),在onload处理程序中,我将执行以下操作:
// get reference to body
var body = document.getElementsByTagName('body')[0];
// listening for onload event
body.addEventListener('load', loadHandler);
function loadHandler() {
// get reference to our description text area
var descriptionTextArea = document.getElementById('descriptionTextArea');
// call method with reference to descriptionTextArea as parameter
characterCount(descriptionTextArea);
}
这样,我们在页面加载时调用“characterCount”方法,它应该在无需用户交互的情况下正确计算字符数。将此
添加到您的body标记中,并将textarea的id设置为“text”“请发布正确的javascript.thx,它已经编辑过很多次了!我试图将该事件放在textarea上,这对我来说很愚蠢。这不起作用,因为有两个原因,当textarea被加载时,charcount span不起作用。此外,textarea不存在onload事件。它也可以工作,但与body调用方法有点混淆。