2014-11-21 5 views
0

HTML 파일에 포함 된 브라우저에 외부 자바 스크립트 파일을 표시하려고했습니다.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> 

을 그리고 아직도 브라우저 나 콘솔도에 표시하는 결과가 없습니다 :이 내가 이런 짓을하도록 html 태그 내에서 특정 함수를 호출해야 becuase 발생하는 것을 생각했다.

페이지에 대화 형 기능을 추가하기 위해 이벤트 처리기를 태그 내에 포함시켜야하는 방식으로 외부 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

빈 문자열에 해당하는 값을 반환하는 함수 인'toString' 속성을 가진 객체 인 'myCard'이외의 다른 결과를 제공하는 것은 생각지도 못합니다. 그래서 문제가 무엇이든, 당신이 우리와 공유하지 않은 대본에 있습니다. – Quentin

+0

'cardGame.js '의 내부 내용은 무엇입니까? – TheDude

+0

'

답변

-1

당신은 잘못된 구문이 자바 스크립트 파일하지만 인라인을 포함하고 있습니다. 이 올바른 것입니다 :

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

내가 myCard 생각은 숫자 또는 toString 방법을 사용하기 위해서는 부울 변수 유형입니다하지만 아무것도 콘솔에 표시되지 않은 경우가 맞습니다보다.

+1

. 특히 위의'document'를 생략하면 JavaScript는'getElementById()'라는 함수가없는'window' 스코프를 가정합니다. – candu

+1

아니요, 양식 컨트롤의 onclick 속성에있을 때가 아닙니다. [이 데모] (http://jsbin.com/tuyumajuqa/1/edit?html,output)를 참조하십시오. – Quentin

관련 문제