[英]Asp.net MVC 5, Html.Checkbox on click event not working
因此,我正在構建一個界面,該界面根據選中的復選框將事件添加到日歷。 目前,我可以像這樣觸發事件:
@Html.CheckBox("Mon1D", new { htmlAttributes = new { @class = "form-control" } })
和JS:
$('#Mon1D').click(function () {
//some code
});
很好嗎? 錯誤。 如果采用這種方法,則必須對所有42個復選框進行一個(幾乎)相同的功能。 我寧願選擇一種適合所有功能的函數來處理復選框的onclick事件。 我雖然有點JavaScript,但是我不太清楚為什么我的onclick無法啟動。
onclick看起來像這樣:
$myFunction(function () {
//some code
});
和復選框
@Html.CheckBox("Mon1D", new { htmlAttributes = new { @onclick = "myFunction()", @class = "form-control" } })
如果采用這種方法,則必須對所有42個復選框進行一個(幾乎)相同的功能。
采取不同的方法。 jQuery還有另一個選擇器,它允許按這樣的類進行選擇:
$('.form-control').click(function (event) {
// to get the element that fired the event
alert(event.target.id);
// or you can use the 'this' variable like below
var $element = $(this);
// And then you can get any attribute of the element like this
var id = $element.attr('id');
var someOtherAttribute = $element.attr('whateverYouNeed');
});
this
是指觸發事件的元素。 使用$(this)
會將其包裝為jQuery對象,然后您可以在其上使用所有jQuery可用的調用。
任何具有form-control
類的元素,其click
事件都將被該元素攔截。
在這里解決了我的問題:“ onclick”沒有觸發,因為它位於“ htmlattributes”類的內部。 需要匿名定義。 像這樣:
@Html.CheckBox("someID", new { @onclick = "myFunction();", htmlAttributes = new { @class = "form-control" } })
編輯:添加上述代碼的HTML結果。
<input htmlAttributes="{ class = form-control }" id="someID" name="someID" onclick="myFunction();" type="checkbox" value="true" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.