2016-04-09 22 views
0

我正在學習JQuery,我無法弄清楚爲什麼沒有JQuery行執行,而JavaScript行。 當我用瀏覽器打開它時,控制檯顯示「hello world」和「undefined」。如果我把這些行放在控制檯中,它們按預期執行。 這裏是我的代碼:`爲什麼jquery沒有工作,當js呢?

<!DOCTYPE html> 
<html lang="en"> 
    <meta charset="UTF-8"> 
    <title> cim </title> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> $('div:nth(0)').attr("class","marked") </script> 
    <script> 
     $(document).ready(funk()) 
     function funk() { 
     $("div").css("border", "3px solid red"); 
      console.log("hello world"); 
      $("div:nth(0)").attr("class","marked"); 
      console.log($("div:nth(0)").attr("oo")); 
      $("div").append("LLLLLLLLLLLLLLLLLLLLL"); 
     } 
    </script> 


</head> 
<body> 
<div oo="ooo"> 
<p> blah </p> 
<p> blah <br></p> 
<p>blah</p> 
</div> 
<div> 
    <p> asd</p> 
    <p> asd</p> 
    <p > asd</p> 
</div> 
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script> 
</body> 
</html>enter code here` 
+2

你爲什麼包括在第2個不同版本的jQuery? – Pointy

+2

另外:'$(document).ready(funk);'not'funk()' - 當你包含'()'時,你*調用函數。 – Pointy

+0

我看到'',但沒有'' –

回答

1

變化$(document).ready(funk())這個$(document).ready(function() {funk();});

+1

或者只是'$(document).ready(funk)'。過分複雜化沒有意義。 – Xufox

4

幾個問題

  1. 您包括jQuery的兩個版本(沒有必要的
  2. 您無法在一個script元素中運行代碼並鏈接到外部文件。因此,第一個內部的代碼會被忽略
  3. 您立即執行func法等所有的元素都沒有找到
  4. 沒有:nth選擇的DOM還沒有準備好。無論是:nth-child:eq

你需要的是

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> 
<script> 
    $(document).ready(funk); 
    function funk() { 
     $("div").css("border", "3px solid red"); 
     console.log("hello world"); 
     $("div:nth(0)").attr("class","marked"); 
     console.log($("div:eq(0)").attr("oo")); 
     $("div").append("LLLLLLLLLLLLLLLLLLLLL"); 
    } 
</script> 
相關問題