我有一个用javascript编写的函数,我想在我的ruby on rails控制器(.rb)中调用(使用)。函数用optgroup
动态创建并填充一个select我该如何把它翻译成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]); }
}
}
你不可能做到这一点,除非通过一些特别折磨的黑客攻击。在Rails中,控制器不能看到视图的内部。即使可以,它也不能从中提取Javascript并以某种方式在自己的本地绑定上下文中运行。即使可以,你也不会想要这样做,因为这严重违反了MVC模式。
如果你绝对想这样做,它可能涉及以下组合:
-
从客户端,POST包含JS函数的字符串
-
计算并解析JS
-
将JS转换为Ruby字符串
-
在控制器的本地上下文中计算Ruby字符串
那是大量的工作。相反,模型应该在这里完成繁重的工作,并依赖控制器给它指令,然后将其输出传递给视图。