2017-07-20 19 views
0

對於問題抱歉,我無法弄清楚。 如果:單擊元素中的目標javascript功能

<body onclick="myFunction(event)"> 
<p>Paragraph</p> 
<h1>This is a heading</h1> 
<button>This is a button</button> 

<p id="demo"></p> 

<script> 
function myFunction(event) { 
    var x = event.target; 
    document.getElementById("demo").innerHTML = x.tagName; 
} 
</script> 
</body> 

我怎麼能顯示函數的結果在當前的HTML元素,我點擊了?不在「演示」中。

+3

'x.innerHTML'? –

+0

'x'是一個標籤名稱,我試過'document.getElementsByTagName [0] .x.innerHTML = x.tagName;' - 不起作用 –

+1

@MichalKotus,使用'x.innerHTML = x.tagName;'這就是蘇雷什阿塔*在說什麼。 – Ionut

回答

0

該函數沒有返回任何結果。但在一般情況下,如果你嘗試設置您剛纔單擊以「東西」的對象的innerHTML,你應該能夠做到

event.target.innerHTML = 'something' 
1

希望你能與event.target.nodeName

<body onclick="myFunction(event)"> 
<p>Paragraph</p> 
<h1>This is a heading</h1> 
<button>This is a button</button> 

<p id="demo"></p> 

<script> 
function myFunction(event) { 
    var x = event.target; 
    x.innerHTML = x.nodeName; 
} 
</script> 
</body> 
+0

*如何顯示當前HTML元素中的功能結果,我點擊了哪個?不在「演示」中。* ...你誤解了這個問題嗎? – Ionut

+0

我不想在'document.getElementById(「demo」)'中得到結果,但是如果我點擊'H1',我需要結果在'

'元素 –

+0

@MichalKotus,你收到了一個很好的答案以上,另一個是好的),也是一個很好的評論(你的問題中的第一個)。問題是什麼? – Ionut

1

你做必須改變你的HTML代碼中:

onclick="myFunction(this);" 

在你的情況將是:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
    <title>Document</title> 
</head> 
<body> 
    <input type="button" onclick="mFunction(this);" ID='TER' value="Heeeey"> 
</body> 
<script> 
    function mFunction(obj){ 
     obj.value = "My Result" ; 
    } 
</script> 
</html>