![](/img/trans.png)
[英]how to pass ID value onclick function from anchor tag by click on image using MVC?
[英]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 me
的img
標簽,記住 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.