2010-10-13 23 views
1

我是新来的JQuery所以这个问题可能是一个明显的例子,但我有一些附加文本到什么是已经在输入框中:JQuery的 - 找到之前的字符

$('a.blog_category').click(function(){ 

    var current_value = $('#id_category').val(); 

    $('#id_category').val(current_value + ', '+ this.text); 
    return false 
}) 

我会喜欢添加一个if子句听起来像这样:

“如果行末已经有一个逗号,请不要添加逗号。” “如果还没有逗号并且它不是输入文本中的第一项,请添加逗号。”

我希望这是有道理的。

感谢您的任何帮助事先。

回答

1

不那么肯定,如果jQuery有它的辅助功能,但你可以在此使用普通的JavaScript具有以下实现:

if (current_value.charAt(current_value.length - 1) != ',') { 
    current_value = current_value + ','; 
} 
+0

或者更确切地说,current_value + = ''; – 2010-10-13 00:18:46

+0

这对条款#2做了一些修改,给了我想要的东西:if(current_value.length!= 0 && current_value.charAt(current_value.length - 1)!=',')current_value = current_value +','' ; }谢谢! P.S:如何在评论中添加换行符? – MonkeyBoo 2010-10-13 16:45:33

+0

@MonkeyBoo〜再行休息,我真的不知道。一直试图弄清楚自己。 :D – 2010-10-13 22:46:52

1

下面是与我将如何做到这一点使用正则表达式的一个更新的功能。

+0

我不知道你为什么使用正则表达式,或为什么一个字符类,而不是'/,$ /'。我认为“这不是输入文本中的第一项”意思是,盒子里已经有东西了。我从一开始就没有看到关于逗号的特殊处理的讨论。 – 2010-10-13 00:25:32

+0

只是个人喜好。我喜欢在任何可能的地方使用字符类。但是,我已经从他们的答案中删除了他们。而我只是试图尽可能匹配他的规格。我想这是多余的。但这就是为什么。 – Alex 2010-10-13 00:29:22

1

最简单的方法就是编写逻辑来检查您提到的所有内容。选择器可能有更清晰的方式,但我不得不花更多的时间思考这个问题。但做这样的事情应该可以工作:

$('a.blog_category').click(function(){ 

    var current_value = $('#id_category').val(); 

    if (current_value.charAt(current_value.length - 1) != "," && current_value.indexOf(",") > -1) 
{ 
    $('#id_category').val(current_value + ', '+ this.text); 
} 
else 
{ 
    $('#id_category').val(current_value + this.text); 
} 
    return false 
}) 

编辑:跳过上面。我想你只是在寻找这样的东西,所以也许这会更好。没有逻辑真的需要:

$('a.blog_category').click(function(){ 

    var current_value = $('#id_category').val(); 
    var parts = current_value.split(","); 

    parts.push(this.text); 

if (parts[0] == "") 
    parts.splice(0,1); 

    $('#id_category').val(parts.join(",")); 

    return false 
})​ 
+0

这将永远需要有一个逗号('> -1'),所以你不能添加第一个。 – 2010-10-13 00:26:35

+0

@Matt是的,我意识到这一点。但这就是在这个问题中解释的那样。但是,无论我是否重新将它变得更干净。 – spinon 2010-10-13 00:27:35

+0

是的,这个问题肯定可以用一些说明。 – 2010-10-13 00:30:54

0

尝试:

$('a.blog_category').click(function(){ 

    var current_value = $('#id_category').val(); 

stringArray = current_value.split(","); if(stringArray.length>= 1) { 

//Split the string into an array and check the number of items in array 

if (current_value.charAt(current_value.length)!=","){ 

//Check what the last character in the string is - apply comma if needed 

    $('#id_category').val(current_value 
+ ', '+ this.text); 

} } return false }) 
相关问题