点击元素中的目标javascript函数

时间:2017-07-20 08:02:53

标签: 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 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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>

答案 2 :(得分:0)

该函数在没有返回任何内容的意义上没有结果。但总的来说,如果你试图将你刚刚点击的对象的innerHTML设置为'某事'你应该能够做到

event.target.innerHTML = 'something'