繁体   English   中英

使用图像标签通过“onclick”传递 function

[英]Using image tag to pass a function with 'onclick'

单击图像时,这段代码应更改段落中的文本。 但是,onclick function 不起作用,文本保持不变。 请看代码:

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";
}

 <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>

可以分享完整的源代码吗? 我试过了,效果很好。 您是否将 JavaScript function 包装在脚本标签中?

尝试在图像外部添加一个 div 并在其上移动 onclick,如下所示:

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

但是它也应该在 img 上正常工作

您的代码正在运行。

可能值得考虑更改触发事件的方式,内联onclick事件可能难以跟踪。 您可以使用jquery通过使用引用$("img#me")click事件添加到图像标签(这会找到所有带有 id meimg标签,记住 id 应该是唯一的,因此您可以使用$("#me") )。

您也可以 select 以相同的方式更改段落,使用选择器$("#text")然后 function .text()更改其中的文本,如果您需要该功能,则使用.html()

为了回答的目的,我还使用了指向占位符图像的链接。


 // Attach click event to 'img' tag with id 'me' $("img#me").click(function() { // Change text $("#text").text("You clicked the button"); // Or you can use the following if you need to add HTML: //$("#text").html("You clicked the button"); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <main class="tvfull"> <p id="text"> to be changed</p> </main> <section class="buttons"> <img id="me" src="https://via.placeholder.com/150"> </section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM