我现在有一个页面,上面有一定数量的下拉菜单(4),这些下拉菜单用于从列表中选择数据并提交。它用于选择锦标赛球队,所以目前我只能创建一个有 4 支球队的锦标赛。
我想更改它,以便页面仅显示一个下拉列表,内容类似于 Enter a number of teams
例如,用户选择4/8/16/32。根据用户选择的数字,页面应该生成这个数量的下拉菜单。
我很难做到这一点,无论用户选择什么数字,页面都需要渲染一定数量的下拉菜单并相应地命名它们,即 #team1, #team2, #team3
.
有什么想法可以做到这一点吗?
这是我目前使用 Jade 模板的下拉菜单,如果使用 Jade 造成任何困惑,很抱歉,但很容易理解它是什么:
div.newMatch
form.form-horizontal(action='/tournament', id="tournamentForm")
div.row
label.control-label(for="tournamentName") Tournament Name:
div.controls
input#tournamentName.input-mysize(type="text")
div.row
label.control-label(for="team1") Team 1:
div.controls
select#team1(style='width: 160px;')
include teamsDropDown
div.row
label.control-label(for="team2") Team 2:
div.controls
select#team2(style='width: 160px;')
include teamsDropDown
div.row
label.control-label(for="team3") Team 3:
div.controls
select#team3(style='width: 160px;')
include teamsDropDown
div.row
label.control-label(for="team4") Team 4:
div.controls
select#team4(style='width: 160px;')
include teamsDropDown
我尝试过的:
div.row
label.control-label(for="tournamentName") Tournament Name:
div.controls
input#tournamentName.input-mysize(type="text")
div.row
label.control-label(for="nTeamSelector") Tournament Size:
div.controls
select#nTeamSelector(style='width: 160px;')
option Please select...
option 2
option 4
option 8
option 16
option 32
div.row.hidden#rowTemplate
label.control-label(for="team") Team:
div.controls
select#team1(style='width: 160px;')
include teamsDropDown
div.row#rowContainer
script(type='text/javascript')
$("#nTeamSelector").change(function(){
var nTeams = $("#nTeamSelector").val(); // Get the value of the team selector that you use
$("#rowContainer").empty() // Delete all existing dropdowns
for (var i=0; i<nTeams; i++){
var newRow = $("#rowTemplate").clone(); // Exact copy of the element generated by Jade
/*
* here you should change all the little fields that
* make the dropdowns different. For example:
*/
newRow.children(".control-label").setText("Team "+(i+1)+":");
$("#rowContainer").append(newRow);
}
});
最佳答案
Jade 不仅是服务器端:您还可以编译 Jade 模板来运行客户端。如果我运行:
$ jade --client template.jade
我将得到一个 template.js
文件,其中包含一些我可以在客户端使用的代码(只要我包含 runtime.js
)。生成的 JavaScript 文件将声明一个名为 anonymous
的函数,您可以将局部变量传递给模板,以便像往常一样运行。
如果我有一个包含以下内容的模板文件:
div.row
label.control-label(for=id) Team 1:
div.controls
select(id=id, style='width: 160px;')
include teamsDropDown
然后,假设它不使用变量,您几乎可以使用正常的代码进行附加:
$(anonymous({id: "team" + (teamCounter++)})).appendTo("#tournamentForm");
(或者类似的东西;我相信你能弄清楚)
顺便说一句,如果您使用 Node.js 和 Browserify 1,则可以使用 simple-jadeify
使编译更容易。
关于Javascript - 根据输入显示 'n' 数量的文本框(由 jade 生成)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992431/