正确的方法来实现这一结果?

时间:2014-05-02 19:37:51

标签: jquery variables jslint jshint

所以我目前有这段代码:

if(direction === "right" ) { var signOne = '-'; var signTwo = ''; }
if(direction === "left" ) { var signOne = ''; var signTwo = '-'; }

innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left

右侧或左侧通过该函数传递。而我想要发生的事情,并且按预期工作的是,如果给出的函数说得对,那么它会使两个左值减去,如果函数是用" left"然后它给出正值。

正如我所说,一切正常但JSHint / Lint会引发错误,a)变量被定义两次,b)变量被用于范围之外。是否有一种更简洁的方法来实现我想要的合成正确的东西?

4 个答案:

答案 0 :(得分:2)

您需要在与它们使用的范围相同的范围内声明变量。

var signOne, signTwo;

if(direction === "right" ) { signOne = '-'; signTwo = ''; }
else if(direction === "left" ) { signOne = ''; signTwo = '-'; }

innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left

答案 1 :(得分:1)

var signOne, signTwo;
if(direction === "right" ) { signOne = '-'; signTwo = ''; }
if(direction === "left" ) { signOne = ''; signTwo = '-'; }

innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left

答案 2 :(得分:0)

var signOne, signTwo;

if(direction === "right" ) { signOne = '-'; signTwo = ''; }
if(direction === "left" ) { signOne = ''; signTwo = '-'; }

innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left

答案 3 :(得分:0)

如果您正在学习JS,我强烈建议您阅读Douglas Crockford的 JavaScript:The Good Parts 。他是JSLint的原作者,他的JS风格规则被广泛认为是福音。

关于您的问题,JSLint / Hint给您错误的原因是由于您的变量声明在条件块中重复写入。更好的构造是初始化条件块之外的变量,然后在条件内定义它们。请考虑以下事项:

var signOne, signTwo;

if (direction === "right") {
  signOne = '-';
  signTwo = '';
} else if (direction === "left") {
  signOne = '';
  signTwo = '-';
}

innerWork.not('.active').css({'left': signOne + '450px'}); // Move the not active text to the left
innerImg.not('.active').css({'left': signOne + '370px'}); // Move the not active images to the left