2013-05-14 36 views
1

我已經搜索了很多,並確定有人需要這樣做之前,很抱歉,如果這是重複的。我拿着我認爲是我可以在網上找到的最好的代碼的彙編,並沒有得到任何工作。根據選擇哪個選項運行JQuery動畫

我知道這個結構可能沒有問題,但是有誰知道這是錯誤的。

$(document).ready(function() { 
    $("select[name='selector']").change(function() { 
    $(this).children(':selected').hasClass('three') { 
     $("#mover").animate({ 
     "left": "+=50px" 
     }); 
    }; 
    }); 
}); 

Live example.

+0

從心所欲ually需要一個函數來說明是否不是類.three,然後做一些其他的事情 – mike 2013-05-14 06:12:58

+0

爲什麼你應用類到選項 – PSR 2013-05-14 06:14:50

+0

不知道如何檢查選項的值,更熟悉的檢查類......但如果你可以做到這一點價值將會一樣好。但我基本上需要檢查選項三選擇,動畫一些其他元素 – mike 2013-05-14 06:17:42

回答

1

幾件事情:

  1. 你需要的是一個條件if statement,這是基本的語言。
  2. 只有在使用絕對定位時才考慮left CSS attribute

至於代碼,

#mover { 
    position: absolute; 
} 

$(document).ready(function() { 
    var $selector = $("select[name='selector']"), $mover = $("#mover"); 
    $selector.change(function() { 
     if ($selector.children(':selected').hasClass('three')) { 
      $mover.animate({ 
       "left": "+=50px" 
      }); 
     }; 
    }); 
}); 

You can see it here.

+0

謝謝男人!這有助於並且實際上有很大的意義......我將如何複製另一個函數的功能,如果不是.hasClass的三個..? – mike 2013-05-14 06:28:42

+1

@mike,否定條件呢? 'true' - >'!true' – Alexander 2013-05-14 06:32:13

+1

爲了記錄,您還可以使用'.not()'jQuery函數 – Alexander 2013-05-14 06:33:06

0
$(document).ready(function() { 

$("select[name='selector']").change(function() { 

    if($(this).find('option:selected').text() == "three"){ 

     $("#mover").animate({"left": "+=50px"}); 

    } 
}); 
}); 
+1

爲什麼downvote.Please給我的原因 – PSR 2013-05-14 06:35:29

1
$(document).ready(function() { 
    $("select[name='selector']").change(function() { 
     if($(".three:selected",this).length>0){  
      $("#mover").animate({"left": "+=50px"}); 
     }; 
    }); 
}); 

這裏:http://jsfiddle.net/kpT3b/