我该如何修饰这个冗长的jquery? [英] How can I elegantize this verbose jquery?

查看:79
本文介绍了我该如何修饰这个冗长的jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取选中复选框的值(一次只能选中一个复选框),并且我有以下冗长的代码可以做到这一点:

I need to get the value of the checked checkbox (only one is allowed to be checked at a time), and I have this verbose code to do so:

if (!checkboxSelected) {
    return;
}

if($("#ckbx_produceusage").is(':checked')) {
    rptval = $('#ckbx_produceusage').val();
}
else if($("#ckbx_deliveryperformance").is(':checked')) {
    rptval = $('#ckbx_deliveryperformance').val();
}
else if($("#ckbx_fillrate").is(':checked')) {
    rptval = $('#ckbx_fillrate').val();
}
else if($("#ckbx_pricecompliance").is(':checked')) {
    rptval = $('#ckbx_pricecompliance').val();
}
setEmailAndGenerateValsForUnitReportPair(unitval, rptval);

有没有一种方法可以使这段代码更冗长而又不会变得晦涩难懂?我想到了将一个类动态添加到选中的复选框,然后将其从以前添加了该类的任何类中删除,然后根据当前使用该类修饰的那个来获取rptval.不过,这看起来有点像臭味或Rubegoldbergesque,所以我正在寻找更好的解决方案.

Is there a way I can make this code less verbose without making it ungrokkable? I thought of dynamically adding a class to the checkbox that is checked, and then removing it from any that previously had that class added, and then getting the rptval based on which one is currently decorated with that class. That seems a bit smelly or Rubegoldbergesque, though, so am looking for a better solution.

对于T.J. Crowder,这是HTML(Razor/ASP.NET MVC样式):

For T.J. Crowder, here is the HTML (Razor/ASP.NET MVC style):

@foreach (var rpt in reports)
{
    @* convert id to lowercase and no spaces *@
    var morphedRptName = @rpt.report.Replace(" ", string.Empty).ToLower();
    <input class="ckbx leftmargin8" id="ckbx_@(morphedRptName)" type="checkbox" value="@rpt.report" />@rpt.report
}

推荐答案

$(function()
{
...
// IF (these are the only elements that id starts with ckbx_) THEN
    rptval = $('[id^=ckbx_]').filter(':checked').val();
// ELSE
    // this syntax is more maintainable than $('#ckbx_produceusage, #ckbx_fillrate, ... selectors à la queue');
    rptval = $('#ckbx_produceusage').add('#ckbx_fillrate').add('#ckbx_deliveryperformance').add('#ckbx_pricecompliance').filter(':checked').val();
// FI
...
});

这篇关于我该如何修饰这个冗长的jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆