我正在尝试创建一个页面,用户在下拉列表中选择一个项目,然后创建一个重复的下拉列表。一旦选择了项目,最后一个下拉列表总是需要创建一个新的下拉列表。
使用以下javascript代码
<script type="text/javascript">
$(document).ready(function () {
$(function listselect() {
if (x == null) {
var x = 1;
}
//need to increment x after the completion of the following funciton so the function will trigger on different drop-down lists
$('#FooId' + x).change(function q() {
$('#FooId' + x).clone().attr('id', 'FooId' + (++x)).attr('name', 'Selected').insertAfter('#FooId' + (x - 1))
//return x;
});
//return x;
});
});
</script>
和剃刀html
<div class ="container">
<div class="label">
@Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
@Html.DropDownList("FooId", Nothing, "--Select--", New With {.Name = "Selected", .Id = "FooId" & "1"})
//@*@Html.ValidationMessageFor(Function(model) model.Foo)*@
</div>
</div>
我能够创建第一个列表克隆本身,但是如何从函数q返回x以便它可以被它自己的函数使用(当在Foo1中选择一个项目时,函数q需要触发,然后是Foo2,等)。
(对不起,如果这没有意义,我不确定如何说出来。我对编码很新)。感谢。
答案 0 :(得分:2)
如果我找对你,你就不需要你的大部分代码了。在这里使用课程更容易。就这样做:
$(document).ready(function () {
$('.foo').on('change', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
});
你的标记部分应该是这样的:
<div class ="container">
<div class="label">
@Html.LabelFor(Function(model) model.Foo, "Foo")
</div>
<div class="foo" id="foo">
@Html.DropDownList("FooId", Nothing, "--Select--", new {name = "Selected", @class = "foo" })
</div>
</div>
我不记得Html.DropDownList签名所以我创建简单的jsfiddle没有它。我希望这就是你所需要的。
我已按照以下方式更正了fiddle:
$(document).on('change', '.foo:last', function(e) {
var newFoo = $(e.target).clone();
$(e.target).after(newFoo);
});
现在它不会添加额外的选择,如果它不是最后一个被更改的选择。