如何让我的条件陈述不那么难看

How to make my conditional statement less ugly

本文关键字:陈述不 条件 我的      更新时间:2023-09-26

我正在努力让下面的代码不那么难看,也不知道该怎么办。你们有什么建议吗?谢谢很多

  if($element.is('builder') || $element.is('#options') ){
     tooltipYPos=yPos + 35; 
    }
  if($element.is('#button')){
     tooltipXPos=xPos - 240; 
    }
  if($element.is('#addn')){
     tooltipXPos=xPos - 295; 
     tooltipYPos=yPos - 80; 
    }  

   if($element.is('#count')){
     tooltipXPos=xPos + 180; 
     tooltipYPos=yPos - 90; 
    } 
   if($element.is('label')){
       tooltipXPos=xPos + 80; 
     tooltipYPos=yPos - 90; 
   } 

一般的解决方法是将问题从代码转移到数据。一种解决方案(如下所示)是在各种ID标签上设置一个JavaScript关联数组,其值为值对X和Y偏移(在某些情况下,其中一个或另一个为0)。在使用时,循环遍历关联数组的键,查找匹配项。如果是,请将关联阵列的X和Y偏移添加到toolTipXPos和toolTipYPos上。

这将使您的偏移量保持在一个位置,并且操作它们的代码简短而简单。

(自然未经测试)

// This can be stashed away anywhere.
var a = {
    '#te_classbuilder':              { X: 0,    Y: 35  },
    '#te_options':                   { X: 0,    Y: 35  },
    '#lesson-details-extend-button': { X: -240, Y: 0   },
    '#asset-list-asset-add-button':  { X: 295,  Y: -80 },
    '#asmnt_option_label_q_count':   { X: 180,  Y: -90 },
    "label":                         { X: 80,   Y: -90 }
}
// Put this where you need the actual evaluation to happen  
jQuery.each(data, function(key, value) {
    if ( $element.is(key) ) {
        tooltipXPos = xPos + value.X;
        tooltipYPos = yPos + value.Y;
    }
});

编辑:更改为循环,以便测试label,而不是#label

另一个选项是使用jQuery的.data函数在元素本身上存储适当的X和Y值,如下所示:

$('label').data({ x: 80, y: -90 });
$('#te_classbuilder, #te_options').data({ x: 0, y: 35 });
$('#lesson-details-extend-button').data({ x: -240, y: 0 });
$('#asset-list-asset-add-button').data({ x: -295, y: -80 });
$('#asmnt_option_label_q_count').data({ x: 180, y: -90 });

然后,当需要修改工具提示位置值时,不需要条件语句。只需从$element中检索xy数据属性。

tooltipXPos = xPos + $element.data('x');
tooltipYPos = yPos + $element.data('y');

当然,这假设可以被分配给$element的任何元素之前都会使用适当的xy值调用.data

您能计算出$element的高度/宽度,然后相应地更改tooltipXPos/tooltipYPos,而不是硬编码delta吗?

如果可以组合条件,请先输入:

if ($element.is('#te_classbuilder, #te_options')) {
  tooltipYPos = yPos + 35; 
}

如果我们不能做出一些大的改变,那么我会这样写:

if ($element.is('#te_classbuilder, #te_options')) tooltip = { x: 0,          y: yPos + 35 };
if ($element.is('#lesson-details-extend-button')) tooltip = { x: xPos - 240, y: 0 };
if ($element.is('#asset-list-asset-add-button'))  tooltip = { x: xPos - 295, y: yPos - 80 };
if ($element.is('#asmnt_option_label_q_count'))   tooltip = { x: xPos + 180, y: yPos - 90 };
if ($element.is('label'))                         tooltip = { x: xPos + 80;  y: yPos - 90 };