简体   繁体   English

页面加载时的 Javascript 字数不是 keyup

[英]Javascript word count on page load not keyup

I have a little bit of javascript that counts the amount of words on a box.我有一点点 javascript 来计算一个盒子上的字数。 The javascript looks like this: 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>

and the form like this:和这样的形式:

<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)" />

Basically the bottom input field shows the amount of words in the upper one.基本上底部的输入字段显示了上面的字数。 But it only does so when you click on the upper box "freebrochureentryform", but i want it to load the amount of words as soon as the page loads not when you click the box.但是只有当您单击上方的框“freebrochureentryform”时才会这样做,但我希望它在页面加载后立即加载单词量,而不是在您单击该框时。 I guess it is to do with我想这与

onKeyUp="cnt(document.brochure.freebrochureentryform,this)" 

But have no idea what to change it to.但是不知道要改成什么。

(Btw way Brochure is the name of my form.) (顺便说一下,手册是我的表格的名称。)

Any help greatly appreciated.非常感谢任何帮助。

Ian伊恩

You can call the cnt() function on window.onload event.您可以在window.onload事件上调用cnt()函数。

And instead of listening to onkeyup event, you can listen to the more appropriate oninput (or onpropertychange for IE) event:而不是听onkeyup事件,你可以听更合适的oninput (或onpropertychange for IE)事件:

JSFiddle JSFiddle

<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);
};

Some instruction:一些指令:

  • var txt=area.value
    • .replace(/^\\s+|\\s+$/g,"") means to trim ; .replace(/^\\s+|\\s+$/g,"")表示trim
    • .replace(/\\s+/g," ") combines series of white spaces (including line feeds) into one (to better split without the need to iterate the splitted array); .replace(/\\s+/g," ")将一系列空格(包括换行符)合并为一个(更好地split而不需要迭代split的数组);
    • .split(" ") split by white space (as you have already done). .split(" ")由空格分割(正如您已经完成的那样)。
  • oninput is introduced in IE9 but has some buggy behavior , so you may want to try onproperychange first; oninput是在 IE9 中引入的,但有一些错误的行为,所以你可能想先尝试onproperychange
  • putting function cnt() and textarea / info in window.onload makes them "safe" inside the closure .function cnt()textarea / info放在window.onload它们在闭包内“安全”。 They can't pollute the global namespace, and things in global namespace can not pollute them.它们不能污染全局命名空间,全局命名空间中的东西也不能污染它们。

onKeyUp triggers only on User Interaction. onKeyUp仅在用户交互时触发。

If you load the side there is no Event KeyUp如果您加载侧面,则没有 Event KeyUp

so instead.所以相反。 Trigger it manually.手动触发。

call cnt(document.brochure.freebrochureentryform,document.brochure.c) on your body manually (or onload )手动(或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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM