简体   繁体   English

有没有优化多个if,else if,else语句的方法?

[英]Are there ways to optimise multiple if, else if, else statements?

Here's my code, is there anyway to somehow loop through the if, else if and else statements to dynamically populate them somehow (without so many statements, or is this considered good practice)? 这是我的代码,是否有某种方式可以循环遍历if,else if和else语句以某种方式动态填充它们(没有那么多语句,或者这被认为是一种好习惯)?

$('input').each( function () {

    var self = $(this)

    if ( self.attr( 'type' ) === 'email' && supportsInputType ( 'email' ) ) {
            self.data( 'fallback', 'email' )
    } else if ( self.attr( 'type' ) === 'url'  && supportsInputType ( 'url' ) ) {
            self.data( 'fallback', 'url' )
    } else if ( self.attr( 'pattern' ) && supportsAttr ( 'pattern' ) ) {
        self.data( 'fallback', 'pattern' )
    }

})

I've omitted my other functions as concentrating on the if/else etc. Thanks for any advice. 我省略了其他功能,而只关注if / else等。感谢您的任何建议。

If you make supportsInputType properly handle any type, you could just do something like this: 如果使supportsInputType正确处理任何类型,则可以执行以下操作:

$('input[type]').each(function() {
    var $this = $(this);

    if (this.type !== $this.attr('type')) {
        $this.data('fallback', type);
    }
});

I would try to craft a selector that grabs the inputs by attribute straight away and get rid of supportInputType . 我将尝试设计一个选择器,该选择器可立即按属性获取输入并摆脱supportInputType Something like this (untested): 像这样(未经测试):

var attrs = ['type=email','type=url','pattern'];

$.each(attrs, function(i,attr) {
  $('input['+ attr +']').data('fallback', attr.replace(/.+=/,''));
});

That should probably work with your current code. 这可能应该与您当前的代码一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM