2010-10-13 21 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 }) 
相關問題