jQuery-计算TEXTAREA中的单词 [英] jQuery - count words in TEXTAREA

查看:90
本文介绍了jQuery-计算TEXTAREA中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我有一个Javascript函数,该函数返回我写到textarea中的单词数,但是由于某些原因,我想使用Jquery编写它.而且,尽管我尝试了一下,但还是没能做到,所以这就是为什么我在这里,如果您能帮助我,我将非常感谢.

Well, I have a Javascript function that returns the number of words that I write into a textarea, but for some reasons, I wanted to write it using Jquery. And, although I tried, I didn't managed to get it, so that's why I'm here, I would be very, very grateful if you could help me.

这是Javascript:

This is the Javascript:

function contar() {
palabras = 1;
if (document.data.texto.value.length === '') palabras = 0;
for (count = 0; count < document.data.texto.value.length; count++) {
    if (document.data.texto.value.substring(count, count + 1) == ' ') palabras++;
}
document.data.cuenta.value = palabras;}

这是我制作的jQuery:

And this is the jQuery I've made:

(function () {
    var palabras = 1;
    if ($("[name=data] textarea[name=texto]").val().length === "") {
        palabras = 0;
    }
    for (i = 0; i < $("[name=data] textarea[name=texto]").val().length; i++) {
        if ($("[name=data] textarea[name=texto]").val().substring(i, i + 1) == ' ')) {
            palabras++;
        }
    }
});

最后,这是我用来显示它的HTML:

Finally, this is the HTML I use to display it:

<form name="data">
    <textarea name="texto" cols="40" rows="4" onkeyup="contar()" onkeypress="contar()"></textarea>
    <br>
    <input type="Text" name="cuenta" size="3" maxlength="3">
</form>

推荐答案

有效的解决方案:

function contar(){
        alert($.trim($('[name="texto"]').val()).split(' ').filter(function(v){return v!==''}).length);
}

filter(function(v){return v!==''})部分删除空字符串.

The filter(function(v){return v!==''}) part removes empty strings.

http://jsfiddle.net/qhaYH/

这篇关于jQuery-计算TEXTAREA中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆