【问题标题】:Using image tag to pass a function with 'onclick'使用图像标签通过“onclick”传递函数
【发布时间】:2021-01-08 19:11:18
【问题描述】:

当点击图像时,这段代码应该改变段落中的文本。但是,onclick 功能不起作用,文本保持不变。请看代码:

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

【问题讨论】:

  • 提供的代码 sn-p 按预期工作...

标签: javascript html jquery css


【解决方案1】:

<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 函数包装在脚本标记中?

【讨论】:

  • header中的script.js是不是包含change函数的文件?如果是,您应该将脚本标签向下移动到正文标签的末尾。此外,您没有将更改功能包含在 window.onload 功能中。
  • 谢谢!现在可以了!在末尾包含脚本标记是一种好习惯吗?如果有,为什么?
  • 很高兴听到!是的。如果您在头部包含脚本并引用任何 html 元素,则由于它们尚未呈现,因此无法访问它们。如果在所有元素之后包含脚本标记,则可以确保 JavaScript 知道这些元素。
【解决方案2】:

尝试在图像外部添加一个 div 并像这样移动 onclick:

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

不过它在 img 上也应该可以正常工作

【讨论】:

    【解决方案3】:

    您的代码正在运行。

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

    您也可以以相同的方式选择要更改的段落,使用选择器$("#text"),然后使用函数.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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多