【发布时间】:2012-01-17 01:40:36
【问题描述】:
我有一个用 javascript 编写的函数,我想在我的 ruby on rails 控制器 (.rb) 中调用(使用)。该函数使用 optgroup 动态创建和填充选择
我将如何将其转换为 Ruby 代码?我的问题是要找到 document.createElement("optgroup"); 之类的替代品
这是javascript代码:
enter function nbFct() {
var clipLists = ["Default", "Recent", "Sticky lists"];
var option1 = ["a", "b"];
var option2 = ["a", "x", "c"];
var option3 = ["f", "e", "c", "d"];
var listType = [];
var optionType = [];
for (var i = 0; i < clipLists.length; i++) {
// create dynamic optgroup from clipLists
listType[i] = document.createElement("optgroup");
listType[i].label = clipLists[i];
// alert(listType[i].label) ;
if(listType[i].label == "Default"){
for (var j = 0; j < option3.length; j++) {
// create options and attach to optgroups
optionType[j] = document.createElement("option");
optionType[j].value = option3[j];
// alert(optionType[j].value) ;
optionType[j].appendChild(document.createTextNode(option3[j]));
listType[i].appendChild(optionType[j]);
}
}
else if(listType[i].label == "Recent"){
for (var j = 0; j < option2.length; j++) {
// create options and attach to optgroups
optionType[j] = document.createElement("option");
optionType[j].value = option2[j];
// alert(optionType[j].value) ;
optionType[j].appendChild(document.createTextNode(option2[j]));
listType[i].appendChild(optionType[j]);
}
}
else{
for (var j = 0; j < option1.length; j++) {
// create options and attach to optgroups
optionType[j] = document.createElement("option");
optionType[j].value = option1[j];
// alert(optionType[j].value) ;
optionType[j].appendChild(document.createTextNode(option1[j]));
listType[i].appendChild(optionType[j]);
}
}
}
// set the default
optionType[1].selected = true;
// clear select menu and append optgroups
var selectMenu = document.getElementById("clipListOption");
while (selectMenu.hasChildNodes()) {
selectMenu.removeChild(selectMenu.firstChild);
}
for (var i = 0; i < clipLists.length; i++) {
if (listType[i].hasChildNodes()) { selectMenu.appendChild(listType[i]); }
}
}
【问题讨论】:
-
我不同意这里的近距离投票。这是一个新手的问题,暴露了对 MVC 工作原理的一些误解,但从表面上看,它并不是一个坏的问题。
-
是的,有点不公平......我是 ROR JS 的新手。
标签: javascript ruby-on-rails select populate optgroup