在 Yii 中进行 onKeyPress 事件的正确方法是什么?
What is the right way to have an onKeyPress event in Yii?
<script type="text/javascript">
function textCnt(textarea, counterID, maxLen)
{
var $cnt = document.getElementById(counterID);
if (textarea.value.length > maxLen)
{
textarea.value = textarea.value.substring(0,maxLen);
}
$cnt.innerHTML = maxLen - textarea.value.length + '/500';
}
</script>
<div class="row">
<div id="counter">
500/500
</div>
<?php echo $form->labelEx($modelAdd,'AdditionalText'); ?>
<?php echo $form->textArea($modelAdd,'AdditionalText',
array('maxlength'=>300, 'rows' => 5, 'cols' =>90, 'name'=>'AdditionalText',
'id'=>'AdditionalText',
'onkeypress'=>'textCnt($this, "counter", 500)',
'onChange'=>'textCnt($this, "counter", 500)', 'type'=>'raw'));
?>
</div>
我有一个 textCnt 函数,它应该计算文本区域的长度,然后从我传递给函数的长度中减去它。我一定是语法错误,因为我收到以下错误“Uncaught ReferenceError: textCnt is not defined
在 HTMLTextAreaElement.onkeypress"
您正在混合使用 PHP var 和 javscript,因此 javascript 代码失败并且您没有函数
你不应该使用 $cnt
但 cnt
function textCnt(textarea, counterID, maxLen)
{
var cnt = document.getElementById(counterID);
if (textarea.value.length > maxLen)
{
textarea.value = textarea.value.substring(0,maxLen);
}
cnt.innerHTML = (maxLen - textarea.value.length) + '/500';
}
并且在您的通话中您应该使用 this
而不是 $this
'onkeypress'=>'textCnt(this, "counter", 500);',
<script type="text/javascript">
function textCnt(textarea, counterID, maxLen)
{
var $cnt = document.getElementById(counterID);
if (textarea.value.length > maxLen)
{
textarea.value = textarea.value.substring(0,maxLen);
}
$cnt.innerHTML = maxLen - textarea.value.length + '/500';
}
</script>
<div class="row">
<div id="counter">
500/500
</div>
<?php echo $form->labelEx($modelAdd,'AdditionalText'); ?>
<?php echo $form->textArea($modelAdd,'AdditionalText',
array('maxlength'=>300, 'rows' => 5, 'cols' =>90, 'name'=>'AdditionalText',
'id'=>'AdditionalText',
'onkeypress'=>'textCnt($this, "counter", 500)',
'onChange'=>'textCnt($this, "counter", 500)', 'type'=>'raw'));
?>
</div>
我有一个 textCnt 函数,它应该计算文本区域的长度,然后从我传递给函数的长度中减去它。我一定是语法错误,因为我收到以下错误“Uncaught ReferenceError: textCnt is not defined 在 HTMLTextAreaElement.onkeypress"
您正在混合使用 PHP var 和 javscript,因此 javascript 代码失败并且您没有函数
你不应该使用 $cnt
但 cnt
function textCnt(textarea, counterID, maxLen)
{
var cnt = document.getElementById(counterID);
if (textarea.value.length > maxLen)
{
textarea.value = textarea.value.substring(0,maxLen);
}
cnt.innerHTML = (maxLen - textarea.value.length) + '/500';
}
并且在您的通话中您应该使用 this
而不是 $this
'onkeypress'=>'textCnt(this, "counter", 500);',