当单击图像时,这段代码应该更改段落中的文本。但是,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";
}
<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函数封装在脚本标记中?
尝试在图像外部添加一个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")
(。
您也可以以相同的方式选择要更改的段落,使用选择器$("#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>