2016-08-15 143 views
-3

當按下按鈕時,我想另一個div標籤出現在用戶的屏幕上。我試過並瀏覽了很多網頁,看看哪裏出了問題。在網頁的控制檯上沒有錯誤。這裏是HTML代碼和JavaScript代碼。JQuery動態html頁面

/*jslint browser: true*/ 
/*global $, jQuery, alert*/ 

$("buttonId").click(function() { 
    var structure = $("<div>Hello world</div>"); 
    $("#newDiv").append(structure); 
    document.getElementById("div01").style.backgroundColor = "red"; 
}); 



<html> 
    <head> 
     <link rel="stylesheet" href="site.css"> 
     <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    </head> 

    <body> 
     <nav> 
      <p class="logo"> Logo! </p> 
      <ul id="ul01"> 
       <li><a href="#" class="active">NewsFeed</a></li> 
       <li><a href="#">Discover</a></li> 
       <li><a href="#">Following</a></li> 
      </ul> 
      <div class="logIn"> 
       <a href="#"> Login </a> 
       <a href="#"> Sign Up </a> 
      </div> 
     </nav> 
     <a id="buttonId" href="#"> Click fo anouther div!!</a> 
     <div id=newDiv> 
      <div id=div01> Hello </div> 
     </div> 
     <script src="operations.js"></script> 
    </body> 

</html> 
+4

'$( 「#buttonId」)'... –

+3

'$( 「buttonId」)'會不符合你的元素。它應該是'$(「#buttonId」)' – Steve

+0

謝謝,它現在可行 – Jack

回答

1

$("buttonId")是將不匹配任何元素(因爲它搜索與標籤buttonId的元件)的選擇器。

您應該將其更改爲$("#buttonId")才能使用。

1

你的代碼有一些錯誤。

$("buttonId").click(function() { 
    var structure = $("<div>Hello world</div>"); 
    $("#newDiv").append(structure); 
    document.getElementById("div01").style.backgroundColor = "red"; 
}); 

在上面的代碼中。 buttonId前缺少#個字符。所以它不會匹配任何東西。這是更正版本

$("#buttonId").click(function() { 
     var structure = $("<div>Hello world</div>"); 
     $("#newDiv").append(structure); 
     document.getElementById("div01").style.backgroundColor = "red"; 
    }); 

此外,在您的HTML中,您已經忘記將雙引號放在newDiv和div01的id外部。這裏是更正後的版本

<html> 
    <head> 
     <link rel="stylesheet" href="site.css"> 
     <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    </head> 

    <body> 
     <nav> 
      <p class="logo"> Logo! </p> 
      <ul id="ul01"> 
       <li><a href="#" class="active">NewsFeed</a></li> 
       <li><a href="#">Discover</a></li> 
       <li><a href="#">Following</a></li> 
      </ul> 
      <div class="logIn"> 
       <a href="#"> Login </a> 
       <a href="#"> Sign Up </a> 
      </div> 
     </nav> 
     <a id="buttonId" href="#"> Click fo anouther div!!</a> 
     <div id="newDiv"> 
      <div id="div01"> Hello </div> 
     </div> 
     <script src="operations.js"></script> 
    </body> 

</html> 
0

看起來好像您在$('buttonId')前面缺少'#'符號。

所以它應該是:?!

$("#buttonId").click(function() { 
     var structure = $("<div>Hello world</div>"); 
     $("#newDiv").append(structure); 
     document.getElementById("div01").style.backgroundColor = "red"; 
    }); 

乾杯,

大衛