我有一個表單,當你點擊/檢查一個特定的單選按鈕時,它顯示或隱藏一些元素。此功能還需要在頁面加載時運行,以防MVC驗證返回後發生錯誤。問題是我在頁面加載時得到了TypeError: Cannot read property 'indexOf' of undefined
,雖然代碼確實有效,但它會在腳本部分中打破它下面的所有代碼。我得出的結論是,我沒有檢查在這裏選擇了哪個單選按鈕:if ($element.attr('class').indexOf('update-type-check-current') !== -1)
。JQuery單選按鈕單擊未捕獲投擲TypeError:無法讀取未定義的屬性'indexOf'
JQuery的:
$(document).ready(function() {
$('#CurrentEmployeeRB input[type="radio"]').click(function() {
clickFunc($(this));
});
clickFunc($('#CurrentEmployeeRB input[type=radio]:checked'));
});
function clickFunc($element) {
var currentEmployee = $('.current-employee');
if ($element.attr('class').indexOf('update-type-check-current') !== -1) {
currentEmployee.show();
}
else {
currentEmployee.hide();
}
}
HTML:
<div class="form-group">
<label class="col-md-2 control-label" for="UpdateType">New or Current?</label>
<div class="col-md-10" id="CurrentEmployeeRB">
<label class="radio-inline">
<input class="btn btn-primary update-type-check-new" data-val="true" data-val-required="Please select whether the employee is new or current." id="UpdateType" name="UpdateType" type="radio" value="New"> New
</label>
<br>
<label class="radio-inline">
<input class="btn btn-secondary update-type-check-current" id="UpdateType" name="UpdateType" type="radio" value="Current"> Current
</label>
<br>
<span class="field-validation-valid text-danger" data-valmsg-for="UpdateType" data-valmsg-replace="true"></span>
</div>
</div>
剃刀:
<div class="form-group">
@Html.LabelFor(m => m.UpdateType, new { @class = "col-md-2 control-label" })
<div class="col-md-10" id="CurrentEmployeeRB">
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "New", new { @class = "btn btn-primary update-type-check-new" }) New
</label>
<br />
<label class="radio-inline">
@Html.RadioButtonFor(m => m.UpdateType, "Current", new { @class = "btn btn-secondary update-type-check-current" }) Current
</label>
<br />
@Html.ValidationMessageFor(m => m.UpdateType, "", new { @class = "text-danger" })
</div>
</div>
是否有不同的方式,我應該這樣做呢?我剛剛開始學習JQuery,並且通過搜索找不到任何可行的替代方案。
你試圖實現什麼? –
再次檢查這一行:'clickFunc($('#CurrentEmployeeRB input [type = radio]:checked'))'。該行需要檢查一個單選按鈕。但是沒有默認選中的單選按鈕。 –
您的HTML –