我有通过 jquery 生成的动态字段。我可以通过选择函数触发器 .change
显示这些字段。每个选择字段都有三个选项生物学
、微积分
和其他-未列出
。当选择值为 3
的 Others-not returned
时,该函数会显示一个隐藏的 div。我的问题是,如果有两个选择字段,其中一个选择了“其他未列出”选项,它将显示所有其他选择的隐藏 div。我想只显示特定选择字段的隐藏 div。 JSFIDDLE
$(document).ready(function() {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_' + i + '"><label>Course # ' + i + '</label><br /><label>Course Name:</label> <select id="coursename_' + i + '" name="coursename_' + i + '" class="ddlcss"><option value="">--- Select ---</option>"'
content += '<option value="1">Biology</option>'; content += '<option value="2">Calculus</option>'; content += '<option value="3">Other - Not Listed</option>'; '"';
content += '</select><div class="hideNewCourse" style="display:none;"><label for="newCourse_'+i+'">Add Course Name to List:</label><input type="text" id="newCourse_'+i+'" name="newCourse_'+i+'"/></div></br></div>';
$(document).on('change',"#coursename_"+i, function(){
if ($(this).val() == "3"){
$(".hideNewCourse").show();
}else{
$(".hideNewCourse").hide();
}
});
}
$('#course_catalog').html(content);
}
});
最佳答案
将选择字段的代码更改为:
if ($(this).val() == "3") {
$(this).parent().find(".hideNewCourse").show();
} else {
$(this).parent().find(".hideNewCourse").hide();
}
<强> jsFiddle example
在您的代码中,$(".hideNewCourse")
将显示或隐藏该类的所有元素。通过使用 $(this).parent().find(".hideNewCourse")
,您只能选择与已更改的选择相关的元素。
关于javascript - 选择特定值时显示隐藏的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20480288/