我想根据表格行更改margin-bottom。但是else if语句总是停在第一个if,即margin-bottom:50px。以下是我的代码。有人请帮忙吗?
jQuery(document).ready(function($) {
if ($('table.variations > tbody > tr').length = 0){
$('div[itemprop="description"]').css('margin-bottom','0');
} else if ($('table.variations > tbody > tr').length = 1){
$('div[itemprop="description"]').css('margin-bottom','50px');
} else if ($('table.variations > tbody > tr').length = 2){
$('div[itemprop="description"]').css('margin-bottom','100px');
} else {
$('div[itemprop="description"]').css('margin-bottom','200px');
}
})
答案 0 :(得分:1)
比较应为==
或最好===
,而不是=
。您正在分配,而不是在使用=
时进行比较。
应该是这样的:
if ($('table.variations > tbody > tr').length === 0){
$('div[itemprop="description"]').css('margin-bottom','0');
} else if ($('table.variations > tbody > tr').length === 1){
$('div[itemprop="description"]').css('margin-bottom','50px');
} else if ($('table.variations > tbody > tr').length === 2){
$('div[itemprop="description"]').css('margin-bottom','100px');
} else {
$('div[itemprop="description"]').css('margin-bottom','200px');
}
尽管如此,它可以像这样提高效率:
var margin;
switch($('table.variations > tbody > tr').length) {
case 0:
margin = 0;
break;
case 1:
margin = 50;
break;
case 2:
margin = 100;
break;
default:
margin = 200;
break;
}
$('div[itemprop="description"]').css('margin-bottom', margin + "px");
注意没有复制的代码,也没有多次评估选择器。
另一种方法是使用查找表:
var marginValues = {0: "0px", 1: "50px", 2: "100px"};
var margin = marginValues[$('table.variations > tbody > tr').length];
if (!margin) {
margin = "200px";
}
$('div[itemprop="description"]').css('margin-bottom', margin);
或者,甚至可以通过计算完成:
var margin, len = $('table.variations > tbody > tr').length;
if (len <= 2) {
margin = len * 50;
} else {
margin = 200;
}
$('div[itemprop="description"]').css('margin-bottom', margin + "px");