2014-11-21 43 views
0

我一直在試圖向包含在HTML文件中的瀏覽器顯示一個外部JavaScript文件。 我嘗試在HTML代碼的頭腳本標記:在顯示包括一個Javascript函數到HTML

<head> 
<meta charset="utf-8"> 
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800,300' rel='stylesheet' type='text/css'> 
<script src="cardGame.js"></script> 
<link rel="stylesheet" href="css/style.css"> 
</head> 

並沒有什麼。我認爲這是存在的監守我有html標籤,所以我做了這個內部調用特定的功能:

<div id="computer-choice"> 
    <label for="computer-choice">Computer choice:</label> 
    <ul> 
     <p id="demo"></p> 
    </ul> 
    <button type="button" onclick="getElementById('demo').innerHTML=myCard.toString()">Click Here</button> 
</div> 

而且還是沒有結果既不瀏覽器也不在控制檯顯示。

什麼是正確的方式來包括外部JavaScript文件的方式,我只需要在標籤中添加事件處理程序來爲頁面添加交互性。

的代碼cardGame.js:

function Card(rank, suit) { 
this.rank = rank; 
this.suit = suit; 

this.toString = cardToString; 
this.createNode = cardCreateNode; 
} 

function cardToString() { 

var rank, suit; 

switch (this.rank) { 
    case "A": 
     rank = "Ace"; 
     break; 
    case "2": 
     rank = "Two"; 
     break; 
    case "3": 
     rank = "Three"; 
     break; 
    case "4": 
     rank = "Four"; 
     break; 
    case "5": 
     rank = "Five"; 
     break; 
    case "6": 
     rank = "Six"; 
     break; 
    case "7": 
     rank = "Seven"; 
     break; 
    case "8": 
     rank = "Eight"; 
     break; 
    case "9": 
     rank = "Nine"; 
     break; 
    case "10": 
     rank = "Ten"; 
     break; 
    case "J": 
     rank = "Jack"; 
     break; 
    case "Q": 
     rank = "Queen"; 
     break; 
    case "K": 
     rank = "King"; 
     break; 
    default: 
     rank = null; 
     break; 
} 

switch (this.suit) { 
    case "C": 
     suit = "Clubs"; 
     break; 
    case "D": 
     suit = "Diamonds"; 
     break; 
    case "H": 
     suit = "Hearts"; 
     break; 
    case "S": 
     suit = "Spades"; 
     break; 
    default: 
     suit = null; 
     break; 
} 

if (rank == null || suit == null) { 
    return ""; 
} 
return rank + " of " + suit; 
} 

var myCard = Card("3", "C"); 
document.write(myCard.toString()); 
+1

我想不出任何會給你描述的結果,除了'myCard'是帶'toString'屬性的對象,而這個屬性是一個函數,它返回的值等於一個空字符串。所以無論你的問題是什麼,它都在你沒有與我們分享的腳本中。 – Quentin 2014-11-21 23:00:11

+0

'cardGame.js'裏面有什麼? – TheDude 2014-11-21 23:00:26

+0

'

回答

-1

您包括JavaScript有錯誤的語法文件,但你的網線。 這是正確的:

<button type="button" onclick="document.getElementById('demo').innerHTML=myCard.toString()">Click Here</button>. 

我猜myCard是一個數字或布爾變量類型toString方法的工作,但如果沒有在控制檯中顯示,比它是正確的。

+1

這個。特別是,通過省略上面的'document',JavaScript假定'window'作用域,它沒有一個名爲'getElementById()'的函數。 – candu 2014-11-21 23:04:39

+1

不,它不 - 當你在窗體控件的onclick屬性 - 請參閱[此演示](http://jsbin.com/tuyumajuqa/1/edit?html,output)。 – Quentin 2014-11-21 23:30:46