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
Add a ment  | 

3 Answers 3

Reset to default 3

Remove 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