我有来自数据库的数据页面:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$base = 'zar';
try {
$db = new PDO('mysql:host='.$host.';dbname='.$base.';charset=utf8', $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$name = 'name';
$pin = 'pin';
$ip = 'ip';
$id = 'id';
$statement = $db->query('SELECT id, ip, name, pin FROM devic');
foreach($statement as $wiersz)
{
?>
<div id = "<?php print($wiersz['id'])?>"
<img class= "obraz" src="css/bulb_off.png" alt="...">
<div class="relayBlock"><span class="relayTitle"><?php print($wiersz['name']) ?> </span>
<button class="btn btn-block btn-lg btn-primary " value="on">Wł</button>
<button class="btn btn-block btn-lg btn-danger " value="off">Wył</button>
</div>
</div>
<?php
}
$statement->closeCursor();
} catch(PDOException $err) {
exit('error: '.$err->getMessage());
}
?>
JS:
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val},
success : function(data) {
if (data == 1) {
$('.obraz').attr({src : "css/bulb_on.png"})
}
else{
$('.obraz').attr({src : "css/bulb_off.png"})
}
}
});
});
});
</script>
现在,如果单击任何按钮,数据库中所有行的图片都会更改。我想这样做,在从数据库中单击特定行的按钮后,图片仅针对该行更改。我知道这是因为每张图片都有相同的图片类,但我可以用不同的方式吗?
答案 0 :(得分:1)
var idParent = getvalueId from the div parent
if (data == 1) {
$('#' + idParent +' .obraz').attr({src : "css/bulb_on.png"})
} else{
$('#' + idParent +' .obraz').attr({src : "css/bulb_off.png"})
}
答案 1 :(得分:0)
我添加了更改的代码,它有效: JS:
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function() {
var val = $(this).val();
var idParent = $(this).parent().attr("id");
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val},
success : function(data) {
if (data == 1) {
$('#' + idParent +' .obraz').attr({src : "css/bulb_on.png"})
}
else{
$('#' + idParent +' .obraz').attr({src : "css/bulb_off.png"})
}
}
});
});
});
</script>
感谢@RicardEspinàsLlovet的建议。