当用户将下拉列表从男性到女性的默认值更改时,我试图打开一个弹出窗口(某个对话框)。
我使用了之前帖子的JS代码,但没有任何反应,在inspect元素中,我收到的消息告诉我没有对话框,知道如何使它工作吗?
我也尝试过提醒,但是当我更改下拉列表中的选项时,没有任何反应...
我是JS和Jquery的新手......
public class Ad
{
public int Name { get; set; }
public string Email { get; set; }
public IEnumerable<SelectListItem> Gender
{
get
{
return new[]
{
new SelectListItem {Value = "M", Text = "Male"},
new SelectListItem {Value = "F", Text = "Female"}
};
}
}
Index.cshtml代码。
@model IEnumerable<Ad.Models.Ad>
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://code.jquery.com/ui/1.9.2/jquery-ui.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#M').change(function () {
if ($(this).val() === "F") {
alert("I am an alert box!");
dialog.dialog('open');
}
});
});
</script>
<h3>My APP</h3>
p>
@using (Html.BeginForm())
{
}
@*<br style="margin-bottom:240px;" />*@
@Html.ActionLink("Create", "Create",
null, htmlAttributes: new { @class = "mybtn" })
<p>
</p>
<style type="text/css">
a.mybtn {
background: #fa0088;
}
</style>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DropDownListFor(modelItem => item.Geneder, item.Gender, new { id = "M" })
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
答案 0 :(得分:1)
通常,当没有div为id的对话框时会出现问题。 javascript变量应初始化为dialog = $('#dialog')
<script type="text/javascript">
$(document).ready(function () {
$("#M").change(function () {
alert($(this).val());
alert($(this).val() == "F");
if ($(this).val() == "F") {
alert("I am an alert box!");
//dialog.dialog('open'); //commenting out this line would tell where the problem lies.
}
});
});
</script>
更新:要将其应用于多个选择框,您应该使用类选择器,例如jQuery的.M
而不是id选择器#M
。首先,我们需要为所有选择框提供相同的类 M 。
@Html.DropDownListFor(modelItem => item.Geneder, item.Gender, new { id = "M", @class = "M" })
现在将$("#M").change(function () {
更改为$(".M").change(function () {
。
答案 1 :(得分:0)
$('#M')
替换为$('select')