Javascript 选择时的MVC复制下拉列表
我试图创建一个页面,用户在下拉列表中选择一个项目,然后创建一个重复的下拉列表。选定项目后,最后一个下拉列表始终需要创建一个新列表 使用以下javascript代码Javascript 选择时的MVC复制下拉列表,javascript,jquery,asp.net-mvc,asp.net-mvc-4,Javascript,Jquery,Asp.net Mvc,Asp.net Mvc 4,我试图创建一个页面,用户在下拉列表中选择一个项目,然后创建一个重复的下拉列表。选定项目后,最后一个下拉列表始终需要创建一个新列表 使用以下javascript代码 <script type="text/javascript"> $(document).ready(function () { $(function listselect() { if (x == null) { var x = 1;
<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>
还有剃刀
<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,等等
对不起,如果这没有意义,我不知道该怎么说。我对编码很陌生。谢谢。如果我没弄错,您不需要大部分代码。在这里使用类更容易。就这样做吧:
$(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>
您的标记部分应该如下所示:
$(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>
现在,如果不是上次更改的选择,则不会添加额外的选择。对于新列表,是否需要一个带有标签和容器的新行?还是只有一个标签,然后有很多下拉列表?谢谢。这很接近我需要的,而且帮助很大。唯一的问题是,只有最后一个选择列表才能创建克隆。例如,列表1创建列表2,列表2可以创建列表3,但列表1将不再创建任何列表谢谢!这非常有效。我还在.clone之后添加了.attr'id',FooId'+++x,为每个选择列表提供一个唯一的id。我还需要将它们转换为组合框,所以我需要唯一的id。谢谢你的帮助!