[英]How to abstract this single case (showing text field based on selection of a drop down list) into a general function in jQuery?
这是我关于SO的第一个详细问题。
嗨,我有一个表单,并且有很多实例,当用户在下拉列表中选择“其他”选项时,我想在下拉列表后显示一个文本字段。
我正在使用标准的命名约定,并且想知道,我是否必须具有与文档中的DDL /文本字段对一样多的功能,或者我可以拥有可以调用一类DDL的单个功能? 这是HTML:
<label for="spotter">Spotter:</label>
<select id="spotter" required>
<option value="Snoop Dogg">Snoop Dogg</option>
<option value="MC Escher">MC Escher</option>
<option value="Linus Thorvalds">Linus Thorvalds</option>
<option value="Other">Other</option>
</select>
<br/>
<div id="spotter_other_div"><label for="spotter_other">Other Spotter:</label><br><input type="text" name="spotter_other" id="spotter_other" size="50" required/></div>
这是jQuery / javascript:
$(document).ready(function(){
$("#spotter").change(function () {
//alert("You just changed the value of the #spotter drop down menu.");
if ($(this).val() == "Other" )
//alert("You just changed the value of the #spotter drop down menu to 'Other.'");
$("#spotter_other_div").css("visibility", "visible");
else
$("#spotter_other_div").css("visibility", "collapse");
});
});
包含文本字段的div的初始状态为CSS中的“折叠”。
我正在学习jQuery,现在我知道如何为一般情况做一些事情,我想看看这是否是我可以编写的函数,或者是否必须明确地做。
请注意,该页面正在进行中,因此欢迎您提出任何建议(例如,使用范围而不是使用div来包含文本字段等)。
谢谢!
您可以只将一个函数与某些代码一起使用,然后多次调用(或者,如果您使用相同的id
或class
则调用一次)...因此,函数的用途:可重用的代码位。 这是它的外观。
$(function () { //shorthand for ready in jQuery
//set up your function
function dropDownOther(spotter, spotterDiv) { //function takes two args
$(spotter).change(function () {
if ($(this).val() == "Other") {
$(spotterDiv).css("visibility", "visible");
} else {
$(spotterDiv).css("visibility", "collapse");
}
});
}
dropDownOther("#spotter", "#spotter_other_div"); //call your function
dropDownOther("#otherSelector", "#otherSelectorTwo"); //call it again if necessary
});
我在这里看到两个选择。
例如:
$(document).ready(function(){
// Apply this to every select element
$("select").change(function () {
// Dynamically build up the selector to show/hide
var secondMenuId = '#' + $(this).attr(id) + '_other_div'
if ($(this).val() == "Other" )
$(secondMenuId).css("visibility", "visible");
else
$(secondMenuId).css("visibility", "collapse");
});
});
请注意,这种方法在生成HTML时需要纪律,并且对id进行了适当的分配(自从您提到使用标准命名约定以来,您似乎正在这样做)。
这种方法的优势在于,这是您唯一的代码,无需编写大量处理程序。
Sethen为您提供了更多的灵活性,因为您的id不需要遵循严格的约定(您可以将所需的任何参数作为参数传递),但是确实需要您编写函数调用才能将其附加到所需的每个项目上。
两种技术都是有效的,并有其时间和地点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.