简体   繁体   English

我如何才能更有效地重写

[英]How Can I Rewrite This More Efficiently

I have to believe that there's a better way to write the below code. 我必须相信,有一种更好的方法可以编写以下代码。 Thanks in advance. 提前致谢。

var hProtein = $('#protein-lbl');
var hCarb = $('#carb-lbl');
var hFat = $('#fat-lbl');
var hTotal = $('#totalCalories');

// Normal Calc vars
var nProtein = $('#protein-normal-lbl');
var nCarb = $('#carb-normal-lbl');
var nFat = $('#fat-normal-lbl');
var nTotal = $('#totalCalories-normal');

// Hide calculations until bodyweight is entered
hProtein.hide();
hCarb.hide();
hFat.hide();
hTotal.hide();
nProtein.hide();
nCarb.hide();
nFat.hide();
nTotal.hide();

Perhaps giving the HTML elements a class will work? 也许给HTML元素一个类可以工作?

var $ele = $('.class-name');
$ele.hide();

The best solution is to have the default condition of the page specified in HTML/CSS, so it displays properly at first and you don't have to run a bunch of javascript just to set up the default condition. 最好的解决方案是在HTML / CSS中指定页面的默认条件,因此它一开始会正确显示,您不必运行一堆JavaScript即可设置默认条件。

So, if what you're trying to do is establish the default condition upon page load, change the display style of all these elements to style="display: none;" 因此,如果您要尝试在页面加载时建立默认条件,请将所有这些元素的显示样式更改为style="display: none;" right in the HTML so they start out with the right state. 在HTML中正确显示,因此它们以正确的状态开始。

Or better yet, give them all a common class name and create a CSS style rule so they are all initially hidden. 或者更好的办法是,给它们一个通用的类名,并创建一个CSS样式规则,使它们最初都被隐藏。 Doing this in the markup/CSS will prevent them showing and then hiding as your script runs - they will just start out with the right state. 在标记/ CSS中执行此操作将阻止它们在您的脚本运行时显示然后隐藏-它们只会以正确的状态开始。

CSS: CSS:

.initialHidden {
     display: none;
}

HTML: HTML:

<div id="totalCalories-normal" class="initialHidden"></div>

add common class to element the hide it by this way 将通用类添加到元素中以这种方式将其隐藏

$('.common-class-name').hide()

OR 要么

Put all elements in Single div wrap and hide it by that id 将所有元素放在Single div环绕中,并通过该ID隐藏

I would do this : 我会这样做:

$([
    '#protein-lbl',
    '#carb-lbl',
    '#fat-lbl',
    '#totalCalories',
    '#protein-normal-lbl',
    '#carb-normal-lbl',
    '#fat-normal-lbl',
    '#totalCalories-normal'
].join()).hide();

为什么不将标签包裹在字段集中并隐藏字段

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

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