Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - Using image tag to pass a function with 'onclick'

This piece of code should change the text in a paragraph when the image is clicked. However, the onclick function does not work and the text remains the same. Please see the code:

HTML:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <script type="text/javascript" src="js/script.js"></script>

</head>
<body>

<main class="tvfull">
    <p id="text"> myname </p>

    <section class="tv">
        <img class="tv" src="img/television.png">
    </section>
</main>

<main class="remote">
 
    <section class="remote">
        <img class="remote" src="img/remote_base.png">
    </section>

    <section class="buttons">
            <img  src="img/button_me.png" onclick="change()" id="me">
            
    </section>
</main>


</body>
</html>

JS:

// check if page is fully loaded
window.onload = function() {

}
function change(){
    document.getElementById("text").innerHTML = "You clicked the button";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

<main class="tvfull">
    <p id="text"> to be changed </p>

</main>

<section class="buttons">
            <img id="me" src="https://images.pexels.com/photos/3804997/pexels-photo-3804997.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" onclick="change()">
    </section>
    
<script>
  function change() {
    document.getElementById("text").innerHTML = "text changed!"
  }  
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...