我希望使用jquery显示和隐藏div或控件。我是jquery的新手,需要一些帮助。我有这个下拉列表
@Html.DropDownListFor(model => model.TestType , null, htmlAttributes: new { @class = "form-control"})
和这个div
<div class="divqs">
<div class="form-group" >
@Html.LabelFor(model => model.QuestionSet, "QuestionSet", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("QuestionSet", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.QuestionSet,"" , new { @class = "text-danger" })
</div>
</div>
</div>
我写的脚本是
$(document).ready(function ({
$('.ts').change(function (){
if ($(this).val() == 'Question Set')
{ $('.divqs').hide();}
else
{ $('.divqs').show();};
});
});
但是我在显示页面时出现问题。我收到错误&#34; jajva脚本运行时错误:&#39; $&#39;未定义&#34;。我认为这是一个问题,不包括jquery包,但当我检查捆绑它是在那里。可能是什么问题呢?
答案 0 :(得分:1)
您的代码中似乎存在一些问题。
在您提供的代码中:
$(document).ready(function ({
$('.ts').change(function (){
if ($(this).val() == 'Question Set')
{
$('.divqs').hide();}
else
{
$('.divqs').show();};
});
});
HTML中具有类名.ts
的元素在哪里?
因此,在您的HTML / Razor中,您需要更改此行:
@Html.DropDownList("QuestionSet", null, htmlAttributes: new { @class = "form-control" })
要:
@Html.DropDownList("QuestionSet", null, htmlAttributes: new { @class = "form-control ts" })
此外,您收到错误的原因
&#39; $&#39;未定义
是因为您没有在HTML中引用jQuery,或者至少您没有正确引用它。
答案 1 :(得分:0)
您需要在网页上添加对jquery库的引用
答案 2 :(得分:0)
问题在于您尝试使用JQuery而不将其作为依赖项添加到您的html中。在尝试使用之前,您必须包含JQuery库。 最好从CDN做到这一点:
答案 3 :(得分:0)
你的DropDown应该是这样的
@Html.DropDownListFor(model => model.TestType , null, htmlAttributes: new { @class = "form-control" , id="mydropdown"})
并在你的Jquery
中$(document).ready(function ({
$('#mydropdown').change(function (){
if ($(this).val() == 'Question Set')
{ $('.divqs').hide();}
else
{ $('.divqs').show();};
});
});
您应该始终尝试使用唯一ID来控制元素事件...
答案 4 :(得分:0)
现在我正在加入这个 @ Scripts.Render( “〜/脚本/ jQuery的1.10.2.js”)