gpt4 book ai didi

javascript - php 生成 html 按钮来运行 javascript

转载 作者:行者123 更新时间:2023-11-27 23:25:54 25 4
gpt4 key购买 nike

我想做的是单击按钮并让它更新另一个 div 的背景。这些按钮是使用 php 从文件中的 imgs 生成的。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<title></title>
<style>
button{width: 100%; }
</style>
</head>
<body>
<div id="Navi" style="width: 150px; height: 640px;background: green;">
<?php
foreach (glob("*.png") as $filename) {
echo "<button id='$filename' onclick='change(event);'>".substr($filename, 0, -4)."</button></br>";
}
?>
</div>
<div id="ImgBig" style="height: 640px; width: 640px;margin-left: 150px; margin-top: -640px; background: blue;"></div>
<script>
function change(event){
$("#ImgBig").css("background-image", "url("+event.target.id+")");
}
</script>
</body>

最佳答案

请尝试将 php 目标中的 event 更改为 this,以便将您的 javascript 函数应用于当前项目:

<?php
foreach (glob("*.png") as $filename) {
echo "<button id='$filename' onclick='change(this);'>".substr($filename, 0, -4)."</button></br>";
}
?>

然后在您的 javascript change 函数中,只需删除 target:

function change(event){
$("#ImgBig").css("background-image", "url("+event.id+")");
}

关于javascript - php 生成 html 按钮来运行 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com