我从数据库中提取数据并将其显示在textarea中。我有一个字符倒数javascript。正在为数据库/表格中的每个条目重复textarea。
<SCRIPT type="text/javascript">
<!-- Begin
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
// End -->
</script>
这是php:
echo "<b>$ID : $adname</b><br /><a href=\"?action=deletead&IDnum=$ID\">Delete Ad</a><br /><br />\n";
echo "Preview :<br /><div class=\"adcode\">$adcode</div><br /> \n";
echo "<br />\n";
echo "<form action=\"displayads.php\" name=\"addAD$ID\" method=\"post\">\n";
echo "AD code (can be any type of script) text link, javascript or banner :<br />\n";
echo "Code :<br /><textarea name=\"adcode$ID\" wrap=\"physical\" cols=\"60\" rows=\"5\" onKeyDown=\"textCounter(document.addAD$ID.adcode$ID,document.addAD$ID.remLen$ID,5000)\" onKeyUp=\"textCounter(document.addAD$ID.adcode$ID,document.addAD$ID.remLen$ID,5000)\">$adcode</textarea>";
echo "<br /><input readonly type=\"text\" name=\"remLen$ID\" size=\"3\" maxlength=\"3\" value=\"5000\">Characters Left \n";
echo "<input type=\"submit\" name=\"editad$ID\" value=\"Edit AD Code\"></form>\n";
echo "<br /><hr />";
问题是如何进行onload页面加载事件以使所有具有唯一名称textarea name = \“adcode $ ID \”的textarea反映正确的字符数onload。相反,它现在仅在您更改textarea中的信息时才反映正确的金额。
答案 0 :(得分:1)
快速而肮脏的方法是循环遍历textareas并触发绑定到onkeyup
事件的函数...
(function () {
var textareas = document.getElementsByTagName('textarea'),
i = 0;
for (i = 0; i < textareas.length; i += 1) {
textareas[i].onkeyup();
}
}());
<强>更新强>
是的,这应该在加载时运行,或者至少在textareas渲染之后运行。
function addHandler(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on" + evType, fn);
return r;
} else {
return false;
}
}
addHandler(window, 'load', function () {
var textareas = document.getElementsByTagName('textarea'),
i = 0;
for (i = 0; i < textareas.length; i += 1) {
//fire off the "onkeyup" handler.
textareas[i].onkeyup();
}
});
或:
<!-- this script block should be inserted after all of the textareas. -->
<script type="text/javascript">
(function () {
var textareas = document.getElementsByTagName('textarea'),
i = 0;
for (i = 0; i < textareas.length; i += 1) {
//fire off the "onkeyup" handler.
textareas[i].onkeyup();
}
}());
</script>
答案 1 :(得分:0)
或者你可以在php中处理它:
$adcode = substr($adcode,0,5000);
echo '<input readonly type="text" name="remLen' . $ID . '" ' .
'size="3" maxlength="3" value="' . (5000 - strlen($adcode)) . '">' .
'Characters Left' . PHP_EOL;