我需要多選中所選選項的文本值作爲「句子」返回 - 僅用於連接字符串,用逗號分隔空間。在Rails 3.1(jQuery)中使用CoffeeScript從多選擇選項創建一個句子
的HTML的選擇看起來是這樣產生的:
<select id="foo_bazs_attributes_0_bar_ids" name="foo[bazs_attributes][0][bar_ids][]" multiple="multiple" data-validate="true">
<option value="1">I</option>
<option value="2">Want</option>
<option value="3">a</option>
<option value="4">Sentence</option>
</select>
所以我需要我的函數返回「我想,一,句子」。
要使用jQuery做到這一點,我發現了以下(在http://calisza.wordpress.com/2009/03/29/6-jquery-snippets-you-can-use-to-manipulate-select-inputs/):
var foo = [];
$('#multiple :selected').each(function(i, selected){
foo[i] = $(selected).text();
});
所以我寫了我的CoffeeScript文件中的以下內容:
$.fn.selectedToSentence =() ->
arr = []
$('this :selected').each (i, sel) ->
arr[i] = $(sel).html()
arr.join(", ")
,但它永遠不會返回字符串。
- 編輯 -
我打電話是想: $( '選擇[ID $ = 「_ bar_ids」]')selectedToSentence()
- /編輯 -
- 編輯2 -
在CoffeeScript的網站,它顯示了上述腳本編譯爲:
var $;
$ = jQuery;
$.fn.selectedToSentence = function() {
var arr;
arr = [];
$('this :selected').each(function(i, selected) {
return arr[i] = $(selected).text();
});
return arr.join(", ");
};
- /編輯2 -
我也曾嘗試以下語法:
$(@ :selected).each ...
$('@ :selected').each ...
$("#{@} :selected").each ...
均無功而返。
我已經谷歌搜索了,所以可能用錯誤的搜索條件,因爲我來空。 我覺得這只是一個語法上的東西。我做錯了什麼?
你搖滾,的幫助感謝! – grumpit