我在检查 radio 时正在做一些事情,但是,现在我想在页面加载时做同样的事情,希望不会重复大部分代码。
我为页面加载添加它的原因是因为我正在创建一个编辑/更新页面。第一页用于将表单数据保存到 mysql 数据库,第二页从数据库中获取值并显示保存时的表单,用户可以进行更改并将其保存回数据库。
所以我有这个点击。对于其他 radio 值,它不止于此,但不想粘贴太多。这只是示例:
$("input[name='typeofmailerradio']").click(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
所以我做了一个测试并将所有这些都放入页面代码中:
$("input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
首先,这就是我所说的复制大量代码的意思,其次它并没有真正起作用。它适用于页面加载,但用于点击的代码部分不想再工作了。
我想做的是“或”之类的。类似这样的事情,但不知道该怎么做:
$("input[name='typeofmailerradio']").click(function() || $("input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
顺便说一句,我写的建议解决方案根本不起作用。在加载时不起作用,在单击时不起作用。
不起作用:
$("input[name='typeofmailerradio'],input[name='typeofmailerradio']:checked").click(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
不起作用:
$("input[name='typeofmailerradio'],input[name='typeofmailerradio']:checked").val(function() {
if(this.value == 'Postcards') {
$('#typeofpostcardmaileroptions').show("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
}
//more if/else's for more radio values here
});
这就是我为让它工作所做的...
$(document).ready(function() {
function typeOfMailer() {
if($('#typeofmailerradio1').is(':checked')) {
$('#typeofpostcardmaileroptions').show("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').hide("fast");
}
else if($('#typeofmailerradio2').is(':checked')) {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').show("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').hide("fast");
}
else if($('#typeofmailerradio3').is(':checked')) {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').show("fast");
$('#typeofmaileroptions').hide("fast");
}
else {
$('#typeofpostcardmaileroptions').hide("fast");
$('#snapapartoption').hide("fast");
$('#typeofspecialtymaileroptions').hide("fast");
$('#typeofmaileroptions').show("fast");
}
}
$("input[name='typeofmailerradio']").click(function() {
typeOfMailer();
});
typeOfMailer();
});
最佳答案
您可以使用多个选择器:
$('input[name=foo],input[name=bar]:checked').whatever();
^---separate them with a comma
关于javascript - 我如何使 2 个函数在 jquery 中与 "or"同时工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20202653/