經過許多解決方案的試驗和錯誤發現隱藏和顯示使用基於textarea內容的jQuery的內容我已經結束了近做我想做的一塊腳本。我在MVC 5中這樣做,雖然我不認爲這種困境會有任何後果。根據孩子的內容隱藏或顯示div
我有一個編輯頁面,其中有許多可選的文本區域,可以是空的或有一些文本,這些來自數據庫。我想要做的是默認情況下隱藏它們,如果它們不包含文本。他們被分組,並且可以通過點擊上面的描述文字來切換。
我這是怎麼讓他們分組,顯示一個區:
<div class="togglerDesc">
<p class="pointerToggler"><strong>XXX description</strong></p>
<div class="hiddenContainer">
<div class="optionalArea">
<div class="form-group">
@Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
@Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
@Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
@Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
和腳本我有是:
$(document).ready(function() {
if (!$.trim($(".optionalArea textarea").val()).length < 1) {
$(".optionalArea textarea").parents(".hiddenContainer").show();
}
});
現在這工作得很好,如果眼前的文本區域,Q1p1在我的例子中有文字。但是,如果它是空的,即使其他兩個textareas中都有文本,也不會顯示div。看來我的問題在於,腳本沒有考慮所有的div,只檢查第一個。我怎樣才能改變它,以便將.optionalArea中的所有文本區域考慮在內?
你不能做到這一點的所有服務器並設置視圖模型的一些IsXSectionViewable布爾屬性,然後在如果IsXSectionViewable的剃鬚刀中的該元素上設置display:none。 – Fran
@Fran我甚至沒有想過使用剃鬚刀,我已經在網站的其他位上做了一些非常相似的事情,所以我想盡管是相當新手的,但仍然沿着jQuery路線走下去。如果在幾天內沒有合適的答案使用jquery,我會遵循你的建議。非常感謝! – Wubbler
我想第二個服務器端的方法。基於複選框點擊顯示div很容易。您只需要使用任何邏輯來設置複選框的初始狀態,以便最初隱藏或顯示div。 –