2011-10-18 34 views
1

喜有人可以解釋爲什麼下面的代碼不工作,但在這裏工作,但它在這裏工作http://jsfiddle.net/CDp8t/7/的jQuery/JScript中沒有加載

<html> 
    <head> 
     <title></title> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script> 

<script type="text/javascript"> 
    $("#example").focus(function() { 
     var first = $(this).find("option").eq(0); 
     if(first.val() === "1") { 
      first.remove(); 
     } 
    }); 
</script> 
    </head> 

    <body> 

    <select id="example"> 
     <option value="1">First</option> 
     <option value="2">Second</option> 
     <option value="3">Third</option> 
    </select> 
    </body> 
    </html> 
+0

它在jsfilddle鏈接中工作,因爲在加載選擇標記後加載了javascript部分。 – Birey

+0

如果您使用http,請使用http而不是https「http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js」。使用https工作可能無效(IE)。 – Anoop

回答

2

您試圖訪問你的#示例元素創建

之前

你可以在你的腳本標籤移動到HTML的底部或將jQuery代碼在$(文件)。就緒()函數

5

我想你只需要添加你的事件處理程序,DOM的加載:

$(document).ready(function() { 
    $("#example").focus(function() { 
    var first = $(this).find("option").eq(0); 
    if(first.val() === "1") { 
     first.remove(); 
    } 
    }); 
}); 

當您嘗試將事件附加到它時,<select>元素不存在。

2

我想說的最可能的原因是當JavaScript運行時DOM不會加載到您的頁面上,而是在jsfiddle的沙盒中運行時。嘗試包裝它以等待DOM加載:

$(document).ready(function() { 
    $("#example").focus(function() { 
    var first = $(this).find("option").eq(0); 
    if(first.val() === "1") { 
     first.remove(); 
    } 
    }); 
});