2014-11-21 29 views
-1

我想添加一些文本到一個HTML元素的ID隨機更改幾個不同的情況下爲不同的訪問者。這是什麼問題,如果其他聲明

出於某種原因,我的文本沒有被添加到元素中。

任何人看到我的代碼有什麼問題?

這是我設置的JSBin事物的鏈接。

http://jsbin.com/biresocera/1/edit

<script> 
 
    var linkAnchor = $('#link-anchor'); 
 
    var randShareLink = Math.floor(Math.random() * 5) + 1; 
 

 
    $(document).ready(function(){ 
 
     if (randShareLink === 1){ 
 
      $(linkAnchor).append('case 1'); 
 
     } else if (randShareLink === 2){ 
 
      $(linkAnchor).append('case 2'); 
 
     } else { 
 
      $(linkAnchor).append('case 3'); 
 
     } 
 
    }); 
 
</script> 
 

 
<body> 
 
<div id="link-anchor" style="background-color:red; height:40px; color:white; width:50px;"></div> 
 
</body>

+0

你必須在期末結賬括號沒有開一個去用它 – Maxqueue 2014-11-21 01:58:42

+0

linkAnchor已經是一個jQuery對象。不需要'$(linkAnchor)'。只是'linkAnchor.append()' – 2014-11-21 01:59:25

回答

2

的代碼是細。但是,您的jsbin設置不正確 - 您需要添加jquery庫以使其正常工作。

此外,使用linkAnchor.append,因爲它已經是一個jQuery對象。

http://jsbin.com/zokedozibe/1/edit

+0

你是對的:)愚蠢的我。謝謝。 – psvj 2014-11-21 02:01:38

0

缺少jQuery框架

var linkAnchor = $('#link-anchor'); 
 
var randShareLink = Math.floor(Math.random() * 5) + 1; 
 

 
$(document).ready(function(){ 
 
    if (randShareLink === 1){ 
 
     $(linkAnchor).append('case 1'); 
 
    } else if (randShareLink === 2){ 
 
     $(linkAnchor).append('case 2'); 
 
    } else { 
 
     $(linkAnchor).append('case 3'); 
 
    } 
 
});
<head> 
 
    <script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript" ></script> 
 
</head> 
 

 
<body> 
 
<div id="link-anchor" style="background-color:red; height:40px; color:white; width:50px;"></div> 
 
</body>

http://jsbin.com/biqovedeqe/1/