[英]Renaming param created by javascript
我有一個按鈕,讓我可以在每次按下按鈕時創建額外的輸入字段,在提交表單時將每個輸入字段保存到一個(數組)參數中。
按鈕 erb 如下所示:
<%= button_tag 'Add a new field', id: 'add_correct_answer', type: 'button' %>
而它背后的 JavaScript 看起來是這樣的。
$(document).ready(function() {
// When the add_button is pressed
$('#add_correct_answer').click(function() {
// Container (already created)
var container = $('.buttons-fields');
// Create the input wrapper (input tag + delete button), and append it to `container`
var input_wrapper = $('<div>', { class: 'input-wrapper' }).appendTo(container);
// Create an input tag, and append it to input_wrapper
var input = $('<input>', { name: 'correct_answers[]', type: 'text' }).appendTo(input_wrapper);
// Create the remove button, append it to input_wrapper, and add a click callback to
// remove the input wrapper if it's pressed.
var remove = $('<span>', { text: 'x' }).appendTo(input_wrapper).click(function() {
input_wrapper.remove();
});
});
此函數創建可以使用params[:correct_answers]
調用的params[:correct_answers]
,它等於具有輸入字段內容的數組。
我想要做的是將該參數更改為params[:task][:correct_answers]
。 我怎么做?
我試圖改變:
var input = $('<input>', { name: 'task[correct_answers[]]', type: 'text' }).appendTo(input_wrapper);
它作為參數看起來不錯,但沒有保存任何內容。
您可以創建二維數組而不是一維數組。
int[] a = [23,45,494,599]
數組就像int[] a = [23,45,494,599]
然后你用a[0]
或我確定你知道的任何東西調用。
然而,二維數組有點難。 設置看起來像這樣:
int[] a =
[
[1,4,155,164,23,43],//This one
[8,75,45,3134,45,6],
[143,55,7,8,8754,5],
]
並使用a[0][3]
調用並返回 164。第一個括號選擇我標記為“This one”的大數組內的數組,然后第二個數字括號獲取該數組內的數字。
現在對二維數組的解釋已經完成,真正的答案是:
所以2個想法。 嘗試使用task[][]
的設置並執行類似for(blah)task[I]=correct_answers;
您可能不需要 for 但知道您真正需要什么。 或者您可以嘗試執行task[0][0]=correct_answers
但我不知道它是否可行。 我想我可以,所以我保留了它。
正如 OP 在評論中所說:“事情是:我需要更改參數名稱。參數不是典型的變量,所以像你上面提到的那樣的事情將被認為是非常糟糕的做法。實際可行的方法是分配 params[:correct_answers ] 到 params[:task][:correct_answers],然后在提交表單之前刪除 params[:correct_answers]。”
所以我猜我的方法行不通。 除非你不關心壞習慣>:)
我所要做的就是改變
var input = $('<input>', { name: 'correct_answers[]', type: 'text' }).appendTo(input_wrapper);
進入:
var input = $('<input>', { name: 'task[correct_answers][]', type: 'text' }).appendTo(input_wrapper);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.