[英]javascript error with html textarea
我刚刚在我的页面中添加了一个 textarea,它是另一个页面的“包含”...我有一些脚本在 textarea 中执行计数器...下面是代码:
function characterCounter(spanId, maxLen, inputElement)
{
if (spanId)
{
// Update the counter the user sees.
var whatIsLeft = maxLen - inputElement.value.length;
if ( whatIsLeft < 0 ) whatIsLeft = 0;
spanId.innerText = whatIsLeft;
}
// Restrict user from entering more than the maxlen.
if ( inputElement.value.length > maxLen )
{
inputElement.value = inputElement.value.substring( 0, maxLen );
}
}
我一输入就在这里收到 javascript 错误....任何建议
<textarea id="comment" name="comment" rows="2" cols="125"
onkeypress="characterCounter(commentsCounter,${const['COMMENT_MAX_LENGTH']}, this)"
onkeydown="characterCounter(commentsCounter,${const['COMMENT_MAX_LENGTH']}, this)"
onkeyup="characterCounter(commentsCounter,${const['COMMENT_MAX_LENGTH']}, this)">
</textarea>
<a href="javascript:addComment();"><img src="../images/icon_add.gif" border="0" alt="Add"/></a>
</td>
You have <strong><span id="commentsCounter">${const['COMMENT_MAX_LENGTH'] - fn:length(commentForm.comment)}</span></strong> characters left.<br />
谢谢
这两行说:“对象预期”......在调试器中
onkeydown="characterCounter(commentsCounter,250, this)"
onkeyup="characterCounter(commentsCounter,250, this)">
代替:
onkeydown="characterCounter(commentsCounter,250, this)"
onkeyup="characterCounter(commentsCounter,250, this)">
和
onkeydown="characterCounter('commentsCounter',250, this)"
onkeyup="characterCounter('commentsCounter',250, this)">
和
function characterCounter(spanId, maxLen, inputElement)
{
if (spanId)
和
function characterCounter(id, maxLen, inputElement)
{
spanId = document.getElementById(id);
if (spanId)
就目前而言,您的代码期望 commentsCounter 是一个全局可访问的变量。 为了访问id为commentsCounter的元素,你必须使用document.getElementById
您的 function 看起来期待一个 DOM 节点作为spanID
并且您正在向它传递没有引号的commentsCounter
的 id。 在加载<span id='commentsCounter'>
之后,您可能希望在<script>
标记中的某个位置:
You have <strong><span id="commentsCounter">${const['COMMENT_MAX_LENGTH'] - fn:length(commentForm.comment)}</span></strong> characters left.<br />
<script type='text/javascript'>
var commentsCounter = document.getElementById("commentsCounter");
</script>
然后您不需要修改文本区域的关键事件处理程序,因为commentsCounter
现在是一个适当的非空变量。
下面使用:
<textarea id="comment" name="comment" rows="2" cols="125"
onkeypress="characterCounter(\"commentsCounter\",${const['COMMENT_MAX_LENGTH']}, this)"
onkeydown="characterCounter(\"commentsCounter\",${const['COMMENT_MAX_LENGTH']}, this)"
onkeyup="characterCounter(\"commentsCounter\",${const['COMMENT_MAX_LENGTH']}, this)">
</textarea>
假定为字符串类型的参数必须始终被引用。 如果引号内有引号,那么在 java 脚本中,您可以在 '(单引号)之间使用“(双引号),反之亦然,如果需要,可以选择使用转义字符,就像我在上面的示例中使用的那样。您可以简单地将 \" 替换为 '
谢谢谢伦德拉
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.