2016-05-08 4 views
0

を印刷:JavaScriptを - 私は、次のしている要素の値

<div onclick="updateElementWithValue()" id="element">Value 1</div> 
<div onclick="updateElementWithValue()" id="element">Value 2</div> 
<div onclick="updateElementWithValue()" id="element">Value 3</div> 

JS:私は上をクリックした場合

updateElementWithValue(){ 
//need to add some code here to make the function work! 
alert('This is element : '); 
} 

私が何をしたいのか、例えば次のとおりです。

<div onclick="updateElementWithValue()" id="element">Value 2</div> 

そのdivの値を表示します。上記の場合は、次のようになります。値2

アイデア?

+1

乗算要素に同じIDを使用しないでください: 'ID =「要素」私はあなたが言うかもしれない同じ要素ID – andlrc

+0

@andlrc 'node.addEventListener( 'click'、...);' –

答えて

1

最初に、複数の要素に同じIDを使用しないでください。

2番目:パラメータとしてupdateElementWidthValue(this)を指定します。

機能は次のとおりです。

function updateElementWithValue(element) { 
    alert('This is element: ' + element.innerHTML); 
} 
+0

を印刷したループを持っている' – andlrc

+0

について、彼はDOM要素に同じIDを入れているので、これは常にvalue1を取得します – PacMan

+0

@PacManそれは正しくありません – andlrc

関連する問題