【问题标题】:Textarea char count fail on page load页面加载时 Textarea 字符计数失败
【发布时间】:2013-09-18 22:58:09
【问题描述】:

英语不是我的母语习语,因此请提前为我的语法错误道歉。

我正在使用 javascript 来计算 textarea 的字符,代码工作顺利,显示键入时字符限制减少,使用此代码我在 textarea 上调用了一个 php 方法从数据库调用文本,这里是问题出在哪里,在加载时测试页面时,它会在 textarea 上显示文本,但字符限制保持在 500,当然如果你在 textarea 上键入显示正确的字符限制,它会更改值。

如何在页面加载时显示正确的字符限制?

这是我的代码:

HTML 代码:

<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>

JS 代码:

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),但没有任何变化。

【问题讨论】:

  • 请发布正确的javascript。
  • 谢谢,已经编辑过了

标签: javascript events textarea html


【解决方案1】:

将此&lt;body onload="characterCount(document.getElementById('text'))"&gt; 添加到您的正文标签,并将文本区域的 id 设置为“文本”。

【讨论】:

  • 非常感谢!我试图把那个事件放在 textarea 上,我很傻。
  • 这行不通有两个原因,当加载 textarea 时,charcount span 不是。此外,textarea 不存在 onload 事件。
【解决方案2】:

首先,我将为该文本区域添加一个 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 调用方法有点混淆。
猜你喜欢
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 1970-01-01
相关资源
最近更新 更多