1

我正在创建一个触发不同功能的 if 语句。有没有更好的方法可以完成此功能?

$("#slide01-bttn").click(function() {

    if ($("#slide-1").is('#featured_ul li:nth-child(1)'))
    {
    alert("First Child");
    moveSlideFirstChild();
    }

    if ($("#slide-1").is('#featured_ul li:nth-child(2)'))
    {
    alert("Second Child");
    moveSlideSecondChild();
    }

    if ($("#slide-1").is('#featured_ul li:nth-child(3)'))
    {
    alert("Third Child");
    moveSlideThirdChild();
    }

    if ($("#slide-1").is('#featured_ul li:nth-child(4)'))
    {
    alert("Fourth Child");
    moveSlideFourthChild();
    }
});
4

5 回答 5

2
$("#slide01-bttn").click(function() {
    var slide = $("#slide-1");
    var index = $('#featured_ul li').index(slide);
    var position = ["First", "Second", "Third", "Fourth"][index];
    if (position) {
        alert(position+" Child");
        // assuming they are global functions:
        window["moveSlide"+position+"Child"]();
    }
});

如果你的函数是局部变量,你仍然可以做

    var fn = [moveSlideFirstChild, moveSlideSecondChild, moveSlideThirdChild, moveSlideFourthChild][index];
    if (fn) fn();

但我真的建议将你的 moveSlide 函数参数化,这样你只需要一个将元素作为参数移动的函数:

    moveSlide(slide);
于 2012-09-26T13:44:41.557 回答
2

您当然可以将代码简化为此

var pos = $("#slide-1").prevAll().length;
switch (pos)
{
    case 0:
        ...
        break;
    case 1:
        ...
        break;
    ...
    default:
        ...
        break;
}

但似乎您应该优化将子元素移动到只有一个函数而不是N的方法,这样您就可以进行简单的调用:

var elem = $("#slide-1");

// pass position AND element because you'll likely use it inside
moveSlideChild(elem.prevAll().length, elem);

您当然可以只传入元素并在其中获取位置。并保存一些元素选择,因为您正在执行许多 jQuery 元素选择器调用。这将使您的代码显着更快和优化。

于 2012-09-26T13:45:36.683 回答
1

I think the best thing that you could do would be to paramatize your moveSlide functions

function moveSlide(childNumber) {

    //Grab the child element you are looking for
    //Move it code
}

Really you should be able to do something with the ids on the li to simplify it even more. I'm not sure how the HTML is layed out. if you could provide a fiddle we could probably make more progress.

于 2012-09-26T13:39:24.240 回答
1

您可以使用开关来完成工作:

$("#slide01-bttn").click(function() {
var pos = $("#slide-1").prevAll().length;
switch(pos)
{
case 0:
case 1:
  moveSlide(pos);
  break;
default:
  //code to be executed if pos is different from case 0 and 1
}
}

function moveSlide(childNumber) {

    //Grab the child element you are looking for
    //Move it code
}
于 2012-09-26T13:45:46.703 回答
0

如果moveSlideNChild()都做类似的事情,最好应用一些抽象来减少代码量。然后你可以打电话

var $list  = $('#featured_ul li');             // set here for cacheing
var $slide = $("#slide-1");                    // set here for cacheing

$("#slide01-bttn").click(function() {
    var position = $list.index($slide);
    if( position >= 1 && position <= 4) {      // only want 1 through 4
        alert('Child ' + position);
        moveSlideChild(position);
    }
}
于 2012-09-26T13:49:04.193 回答