[英]Jquery click event for drop down list items
I have a drop down list in an MVC application. 我在MVC应用程序中有一个下拉列表。 When an item in the drop down list is selected (including the same one), I want to trigger a function.
在下拉列表中选择一个项目(包括相同项目)时,我想触发一个功能。 However, the first item in the list can't trigger the function and it should be disabled.
但是,列表中的第一项无法触发该功能,因此应将其禁用。 I have some code below which works initially but after clicking a valid option and then clicking --Select-- again, it still fires the code.
我下面有一些代码,这些代码最初可以工作,但是在单击有效选项然后再次单击--Select--之后,它仍然会触发代码。 How do I fix this?
我该如何解决?
MVC Control MVC控制
@Html.DropDownList("ddlCountries", (IEnumerable<SelectListItem>)ViewBag.Countries, "--Select--", new { @class = "form-control" })
jQuery to trigger the DDL click event jQuery触发DDL点击事件
$('#ddlCountries option:not(:first)').click(function () {
runCode()
});
jQuery to disable the first option jQuery禁用第一个选项
jQuery('#ddlCountries option:contains("--Select--")').attr('disabled', 'disabled');
Get the index of the selected option and check to see if it's greater than 0 on event fire. 获取所选选项的索引,并检查事件触发时它是否大于0。 Indexes are 0 based.
索引从0开始。
$('#ddlcountries').on('change', function() {
var index = $(this).find('option:selected').index();
if (index > 0) {
alert('yay');
runCode();
} else {
alert('nay');
return;
}
})
I deleted the code to disable the first option because I couldn't get it to stay disabled after the first change. 我删除了禁用第一个选项的代码,因为在第一个更改之后我无法使其保持禁用状态。 I modified the jQuery to trigger the event to:
我将jQuery修改为触发事件以:
jQuery('#ddlCountries').find('option:gt(0)').click(function () {
runCode()
});
Then I added styling to the --Select-- box to make it gray. 然后,将样式添加到--Select--框中以使其变为灰色。 You can still click on it but it won't do anything.
您仍然可以单击它,但它不会执行任何操作。 Not exactly what I was trying to do but close enough
不完全是我想做的事,但足够接近
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.