我需要检查名为“ContainterTwo”的 div 是否有附加了类“hd”或“tl”的图像,但我的 if else block 从未执行过。这些图像是名为“图像”的数组中的 html img 标签。我使用随机生成器来刺激抛硬币。
$(document).ready(function(){
var image = ['<img src="heads.jpg" class="hd" height="50" width="50">', '<img src="tails.jpg" class="tl" height="50" width="50">'];
$('#flip').on('click', function(){
var heads = 0;
var tails = 0;
var numToFlip = parseInt($('#number').val().trim());
for(var x = 0; x < numToFlip; x++)
{
var ran = Math.round(Math.random() * (1)) + 0;
$('.ContainerTwo').append(image[ran]);
if($('.ContainerTwo').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
}
})
})
最佳答案
试试这个,
if($('.ContainerTwo').find('img').hasClass('hd'))
{
heads++;
$('.spOne').html(heads);
$('.ContainerTwo').empty();
}
else if($('.ContainerTwo').find('img').hasClass('tl'))
{
tails++;
$('spTwo').html(tails);
$('.ContainerTwo').empty();
}
关于javascript - 如果 else 语句检查并查看某个 img 标签是否附加到 div 将不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278150/