2016-03-27 1 views
-1

私はhtmlを学ぶためにjavascriptで単純なhtmlを作成しようとしています。しかし、私はブラウザでhtmlを実行すると、ボタン1とボタン2の値を取得しようとするとコンソールログに未定義に戻ります。Javascript - HTMLで明白に述べられている要素の価値を得ようとすると、未定義になる

HTML:

<!DOCTYPE html> 
<html> 
<script src="js/Try.js"></script> 
<head> 
    <title>Try</title> 
</head> 

<body> 
    <div class="wrapper"> 
     <div> 
      <a type="button" id="Button1" href="#" value="B1" onmouseover="PutValueLog(this)">Button 1</a> 
      <a type="button" id="Button2" href="#" value="B2" onmouseover="PutValueLog(this)">Button 2</a> 
     </div> 
    </div> 
</body> 
</html> 

Javascriptを:

var tempval; 

function PutValueLog(button){ 
    tempval = button.value; 
    console.log(button); 
    console.log(tempval); 
} 

そして、私が取得コンソールログ:

log image

ことが起こる理由は、誰もが私に言うことはできますか?未定義ではなく、コンソールログのB1またはB2を取得するために必要なことは何ですか?

+0

は私の答えは完璧に動作 –

答えて

2

aタグがあり、inputではありません。したがって、valueを使用してアンカータグの値を取得することはできません。 .getAttribute()関数を使用して、属性の値を取得します。

var tempval; 
 

 
function PutValueLog(button){ 
 
    debugger; 
 
    tempval = button.getAttribute('value'); 
 
    //console.log(button); 
 
    alert(tempval); 
 
}
<div class="wrapper"> 
 
     <div> 
 
      <a type="button" id="Button1" href="#" value="B1" onmouseover="PutValueLog(this)">Button 1</a> 
 
      <a type="button" id="Button2" href="#" value="B2" onmouseover="PutValueLog(this)">Button 2</a> 
 
     </div> 
 
    </div>

+1

おかげで、助けている場合、私に教えてください! – KartuHitam

0

次のようにコードを変更します。

var tempval; 

function PutValueLog(button){ 
    tempval = button.getAttribute("value"); //value is not a defined property of an anchor 
    console.log(button); 
    console.log(tempval); 
} 
関連する問題