How can I correct a bug in the swap image jQuery code?
Code Fighter
I'm trying to create code to swap images in a table based on values in the database. After doing some research on the site, I have this code, modified for my needs. It is not dynamic at this time, because the input data at this time is hardcoded. jQuery doesn't work because I'm missing some point. Very new to jQuery so if you could help point me in the right direction it would be greatly appreciated.
<table>
<tr>
<td>6</td>
<td id="td1">
<img />
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#td1 img').attr('src' function(){
return parseInt($(this).parent().prev().html()) > 5 ? 'src1','/images/clubsTiny.png' : 'src2','/images/blkCross.png';
});
</script>
Alireza Ahmadi
First $('#td1 img').attr('src', function ()
by ,
. Note attr
that two parameters are required, each with ,
.
Then change the condition:
return parseInt($(this).parent().prev().html()) > 5 ? 'src1/images/clubsTiny.png' : 'src2/images/blkCross.png';
Note that the ternary condition isexpression ? 'do true one' : 'do false one'
$('#td1 img').attr('src', function () {
return parseInt($(this).parent().prev().html()) > 5 ? 'src1/images/clubsTiny.png' : 'src2/images/blkCross.png';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>6</td>
<td id="td1">
<img />
</td>
</tr>
</table>
renew
For replacement content img
you can use$('#td1').html(img)
function replace() {
let td = $('#td1');
let img = $("<img />");
img.attr("src", ()=> +td.html() > 5 ? 'src1/images/clubsTiny.png' : 'src2/images/blkCross.png')
$('#td1').html(img)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td id="td1">
6
</td>
</tr>
</table>
<button onclick="replace()">click to replace</button>