admin管理员组文章数量:1316382
I'm simply testing out JavaScript, trying to get a feel for it, and I happened to run into a little trouble along the way. The oncllick attribute isn't doing what I intend for it to do with the "p" tag. I want the paragraph to turn blue when I click it, but the style is changed to blue during loading. Help would be appreciated!
<!DOCTYPE html>
<html>
<body>
<p id="test">This is a test. This is a test.</p>
<script>
var x;
x=document.getElementById("test")
function changeColor()
{
x.style.color="blue";
}
x.onclick=changeColor()
</script>
</body>
</html>
I'm simply testing out JavaScript, trying to get a feel for it, and I happened to run into a little trouble along the way. The oncllick attribute isn't doing what I intend for it to do with the "p" tag. I want the paragraph to turn blue when I click it, but the style is changed to blue during loading. Help would be appreciated!
<!DOCTYPE html>
<html>
<body>
<p id="test">This is a test. This is a test.</p>
<script>
var x;
x=document.getElementById("test")
function changeColor()
{
x.style.color="blue";
}
x.onclick=changeColor()
</script>
</body>
</html>
Share
Improve this question
asked Apr 8, 2014 at 21:41
user3512807user3512807
111 gold badge1 silver badge2 bronze badges
3 Answers
Reset to default 3Remove the parentheses:
x.onclick=changeColor;
The way you have it there, you are calling the function immediately and assigning the result (undefined
) to the onclick
event handler. You need to assign the function itself to the event handler.
Set the onclick handler to the function name:
x.onclick = changeColor
Or call your changeColor
fn inside an anonymous function that you assign to onclick:
x.onclick = function(){changeColor();}
...with the later method you also call other fns if you wanted to.
change color does not have brackets inside it. Try editing it to this...
x.onclick = changeColor;
changecolor() is not correct as it is not a reserved method. For example Date().
本文标签: javascriptOnclick attribute for ltpgt tagsStack Overflow
版权声明:本文标题:javascript - Onclick attribute for <p> tags - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741997699a2410378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论