2017-01-10 38 views
-2

我有这个简单和基本的代码,我在JSFiddle上做过 它似乎没有工作。 我想要做的是将head2 id的innerHTML更改为JavaScript代码中的文本我的简单JavaScript代码不起作用

让我知道您的想法!

P.S这是的jsfiddle所以我没有链接JavaScript文件到我的HTML,因为他们已经将其链接我相信

function clickMe() { 
 
\t var hehe = document.getElementById('head2'); 
 
    hehe.innerHTML = "<strong>I changed the heading!</strong>"; 
 
}
<h1> 
 
This is heading one 
 
</h1> 
 
<h2 id="head2"> 
 
This is heading two 
 
</h2> 
 
<input value="Click me!" type="button" onclick="clickMe">

+10

'的onclick = “clickMe()”'代替'的onclick = “clickMe”'。函数通过'()'调用。 –

回答

2

变化onclick="clickMe"onclick="clickMe()"。你忘了括号

function clickMe() 
 
{ 
 
    var hehe = document.getElementById('head2'); 
 
    hehe.innerHTML = "<strong>I changed the heading!</strong>"; 
 
}
<h1>This is heading one</h1> 
 
<h2 id="head2">This is heading two</h2> 
 
    
 
<input value="Click me!" type="button" onclick="clickMe()">

+0

谢谢!这段代码片段在stackoverflow中工作,但在jsfiddle或notepad上没有。你知道它可能会阻止代码工作吗? – Ushi

0

中的 'onClick' 添加括号你的函数名

0

这里是另一种选择。这只是我的偏好,但我更愿意使用JavaScript处理事件,而不是将onClick属性添加到节点。这是另一种选择。

var myButton = document.getElementById('myButton'); 
 
myButton.addEventListener("click", clickMe); 
 
function clickMe() { 
 
\t var hehe = document.getElementById('head2'); 
 
    hehe.innerHTML = "<strong>I changed the heading!</strong>"; 
 
}
<h1> 
 
This is heading one 
 
</h1> 
 
<h2 id="head2"> 
 
This is heading two 
 
</h2> 
 
<input value="Click me!" id="myButton" type="button">

0

只是使用的onclick =的 “clickMe()”,而不是使用的onclick = “clickMe”

function clickMe() { 
 
\t var hehe = document.getElementById('head2'); 
 
    hehe.innerHTML = "<strong>I changed the heading!</strong>"; 
 
}
<h1> 
 
This is heading one 
 
</h1> 
 
<h2 id="head2"> 
 
This is heading two 
 
</h2> 
 
<input value="Click me!" type="button" onclick="clickMe()">

0

你忘了 “()” 后,致电Javascript函数。这是正确的代码。请享用 :) !

function clickMe() { 
 
\t var hehe = document.getElementById('head2'); 
 
    hehe.innerHTML = "<strong>I changed the heading!</strong>"; 
 
}
<h1> 
 
This is heading one 
 
</h1> 
 
<h2 id="head2"> 
 
This is heading two 
 
</h2> 
 
<input value="Click me!" type="button" onclick="clickMe()">

+0

谢谢!我简直就是在重新登录之前就明白了这一点:P – Ushi