[英]Javascript word count on page load not keyup
我有一点点 javascript 来计算一个盒子上的字数。 javascript 看起来像这样:
<script type="text/javascript">
function cnt(w,x){
var y=w.value;
var r = 0;
a=y.replace(/\s/g,' ');
a=a.split(' ');
for (z=0; z<a.length; z++) {if (a[z].length > 0) r++;}
x.value=r;
if (r > 60) {
x.value='Please reduce the word count';
}
}
</script>
和这样的形式:
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform" onKeyUp="cnt(this,document.brochure.c)"><?php echo $row['freebrochureentryform']; ?></textarea>
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" value="0" size="20" onKeyUp="cnt(document.brochure.freebrochureentryform,this)" />
基本上底部的输入字段显示了上面的字数。 但是只有当您单击上方的框“freebrochureentryform”时才会这样做,但我希望它在页面加载后立即加载单词量,而不是在您单击该框时。 我想这与
onKeyUp="cnt(document.brochure.freebrochureentryform,this)"
但是不知道要改成什么。
(顺便说一下,手册是我的表格的名称。)
非常感谢任何帮助。
伊恩
您可以在window.onload
事件上调用cnt()
函数。
而不是听onkeyup
事件,你可以听更合适的oninput
(或onpropertychange
for IE)事件:
<label>Free brochure from entry:</label>
<textarea name="freebrochureentryform" id="freebrochureentryform">Lorem Text</textarea>
<br />
<label>Brocure Entry Word Count:</label>
<input type="text" name="c" id="c" value="0" size="20" />
window.onload=function(){
function cnt(area,output){
var txt=area.value.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ").split(" ");
if(txt.length>10){
output.value="Please delete some word";
}else{
output.value=txt.length;
}
}
var textarea=document.getElementById("freebrochureentryform");
var info=document.getElementById("c");
if("addEventListener" in window){
if("oninput" in textarea){
textarea.addEventListener("input",function(){
cnt(textarea,info);
},false);
}else if("onpropertychange" in textarea){
textarea.addEventListener("propertychange",function(e){
if((e||event).propertyName=="value"){
cnt(textarea,info);
}
},false);
}else{
textarea.addEventListener("change",function(){
cnt(textarea,info);
},false);
}
}else{
textarea.attachEvent("onpropertychange",function(){
if(event.propertyName=="value"){
cnt(textarea,info);
}
});
}
cnt(textarea,info);
};
一些指令:
onKeyUp
仅在用户交互时触发。
如果您加载侧面,则没有 Event KeyUp
所以相反。 手动触发。
手动(或onload
)在您的身体上调用cnt(document.brochure.freebrochureentryform,document.brochure.c)
)
尝试在 body onload event
上调用cnt(w,x)
function countWords(str) {
let arr = str.split(' ');
let count = 0;
if(arr.length > 0){
for (let i = 0; i< arr.length - 1; i++){
let sentence = arr[0];
let bool = true;
for(let j = 0; j < sentence.length - 1; j++){
let charcode = arr[i].charCodeAt(j);
if((charcode > 64 && charcode < 91) || (charcode > 96 && charcode < 123)){
bool = false;
}
}
if(bool == true){
count += 1;
}
}
}
return arr.length - count;
}
//function calling
countWords("he is a good programer, he won 865 competitions, but sometimes he dont.
what do you think? all test-cases should pass. done-done?");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.