2016-05-01 9 views
-3

私はいくつかの機能をページの$(document).ready(function(){に使用しています。

新しい機能(上に追加)を追加するまで、古い機能(下に強調表示されています)は正常に機能しました。それ以来、彼らはもはや働かない。 いくつかのテストの後、私は古い機能と新しい機能の間でポジションを切り替えると、上に配置された機能だけが機能することに気付きました。

私は以前のものとは別のページで新しい機能を使用していますが、どちらもjavascriptファイルとフッターに含まれています。

home.js:私は "古い機能" を使用して、ページをロードする場合

$(document).ready(function(){ 

// NEW FUNCTION (up/down arrows) 
     var nextListitem; 
     var noOfListItems = $("#select > option").length-1; 
     var curListItem = $("#select")[0].selectedIndex; 
     $("#upArrow").on("click", function(){ 
      // Decrement the selection by one, unless that will be less than zero, then go to the last option 
      nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1; 
      curListItem = nextListitem; 
      $("#select")[0].selectedIndex = nextListitem; 
     }); 


    // OLD FUNCTIONS (count characters left in textarea) 
    window.com_domain = window.com_domain || {}; 
    $(':text,#resort_description').click(function(){ 
     current_input_val = $(this).val(); 
     $(this).select(); 
    }).focusout(function(){ 
     if ($(this).val() == '') { 
      $(this).val(current_input_val); 
     } 
    }); 
    // more old functions 


}); 

TypeError: $(...)[0] is undefined

var curListItem = $("#select")[0].selectedIndex;

が表示されます。

これは(jqueryのを前に呼ばれている)のように、私のフッターがどのように見えるかです:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script> 
    <script src="js/bootstrap-hover-dropdown.min.js'>"></script> 
<script src="js/home.js" type="text/javascript"></script> 
+1

は、あなたが質問に関連していない任意のコードを削除でしたファイルのjs縮小さbootstarpのインポートにmistkeを持っていると思いますか? – evolutionxbox

+1

'id ="を持つ要素がありますか?そうでない場合、そのエラーは関数をそこで停止させます。 – Barmar

+1

ページのHTMLを表示します。 – Barmar

答えて

2

ページのid="select"とは要素がありません場合は、$("#select")は空のコレクションになりますので、$("#select")[0]は未定義になります。 undefined.selectedIndexにアクセスすることはできませんので、その行でエラーが発生し、実行後は何も表示されません。それは準備ブロックに複数の機能を持つこととは関係ありません。

要素が最初に存在するかどうかを確認する必要があります。

if ($("#select").length > 0) { 
    var nextListitem; 
    var noOfListItems = $("#select > option").length-1; 
    var curListItem = $("#select")[0].selectedIndex; 
    $("#upArrow").on("click", function(){ 
     // Decrement the selection by one, unless that will be less than zero, then go to the last option 
     nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1; 
     curListItem = nextListitem; 
     $("#select")[0].selectedIndex = nextListitem; 
    }); 
} 
+0

それは完璧に働いた!ありがとう。 – remyremy

0

は、まず第一に、私はあなたが

script src="js/bootstrap-hover-dropdown.min.js"></script>

+0

ありがとう。それは質問を書くときのちょうどタイプミスでした。訂正 – remyremy

関連する問題