我有这个更改功能,可以将隐藏的类删除或添加到剃刀下拉列表中。 这将检查其中一个下拉列表中的值是否为该字符串,然后在更改时,根据该选择删除或添加该类。
<label class="control-label col-md-4 optional" id="PIdsLabel" for="pIds">PIds</label>
@Html.DropDownList("PIds", allPlacements, new { htmlAttributes = new { @multiple = true, @data_placeholder = "Select", @class = "form-control no-chosen hidden"}})
<label class="control-label col-md-4 optional" id="FLabel" for="FType">FType</label>
@Html.DropDownList("FType", Enum.GetValues(typeof(FType)).Cast<FType>().Select(o => new SelectListItem { Text = o.GetDescription(), Value = o.ToString()}), new { htmlAttributes = new { @multiple = true, @data_placeholder = "Select", @class = "form-control no-chosen hidden"}})
@section Scripts
{
@Scripts.Render("~/js/index-layout")
<script type="text/javascript">
function linkify()
{
jQuery.event.trigger('linkify');
}
(function() {
$(document)
.ready(function()
{
var $typeCell = $('<td></td>');
var $typeField = $('<select></select>')
.attr('class', 'text-box single-line form-control')
.attr('id', 'PType')
.attr('name', 'PCs[0].PType');
@foreach (var item in allPTypes)
{
@:$typeField.append($('<option>').attr('value', "@item").text('@(((PType) item).ToString().Replace("_", " "))'));
}
$typeCell.append($typeField);
$('#PType').change(function (e)
{
if ($('#PType').val() == "Conditional_Locked")
{
alert("Hello");
$('#FType_chosen').removeClass('hidden');
$('#FTypeLabel').removeClass('hidden');
$('#PIds_chosen').removeClass('hidden');
$('#PIdsLabel').removeClass('hidden');
}
else
{
alert("Bye");
$('#FType_chosen').addClass('hidden');
$('#PIds_chosen').addClass('hidden');
$('#FTypeLabel').addClass('hidden');
$('#PIdsLabel').addClass('hidden');
}
});
$(document)
.bind('linkify',
function()
{
doLinkify($elements.$resultDetailView);
});
});
})();
</script>
}
问题是更改事件永远不会被触发。为什么?
.hidden {
display: none;
}
我尝试在浏览器控制台窗口中运行带有更改事件的代码段,它运行正常。我添加了警报,看看它们是否触发,并且当我从控制台窗口直接运行时它运行正常。不是在页面加载并且未检测到选择更改时(除非我直接进入控制台)。
答案 0 :(得分:1)
您的选择是动态的。当自调用函数运行并且绑定更改事件发生时,它没有任何内容可以绑定,因为那时dom元素不在dom上。你需要做的是:
$(document).on({
change: function (e, i) {
//your code goes here
}
}, '#Ptype');
这样做是告诉文档不断地监听名为PType的元素的变化。您可以将此代码放在javascript中的任何位置。这将处理动态元素。