尝试添加特定图像类型的图像计数| jQuery

Attempting to append an image count for specific image types | jQuery

本文关键字:图像 jQuery 类型 添加      更新时间:2023-09-26

我想让这个函数在用户点击时打印小球图片的数量或消防车图片的数量:

function imageCounter (){
var ballCount = 0;
var truckCount = 0;
$('img[src*=ball]').each(function(){
    if($(this).prop("checked")){
        ballCount+=1;
    }     
    $('#radioButtons').append("There are " + ballCount + " ball images.");
 });

$('img[src*=truck]').each(function(){
    if($(this).prop("checked")){
        truckCount+=1;
    }
    $('#radioButtons').append("There are " + truckCount + " truck images.");
    });
}

我觉得我很接近…

我有4个球图像和1个消防车图像。我的代码目前没有给我图像的数值,相反,它为球打印了4次输出消息,为消防车打印了1次。

有什么建议吗?

您只需要将附加消息行移出foreach循环:

function imageCounter() {
  var ballCount = 0;
  var truckCount = 0;
  $('img[src*=ball]').each(function () {
    if ($(this).prop("checked")) {
      ballCount += 1;
    }
  });
  $('#radioButtons').append("There are " + ballCount + " ball images.");
  $('img[src*=truck]').each(function () {
    if ($(this).prop("checked")) {
      truckCount += 1;
    }
  });
  $('#radioButtons').append("There are " + truckCount + " truck images.");
}

我注意到一些事情。第一件事是$(this).prop("checked")将在<img>标记上被调用,除非您将它们设置为在此处未显示的代码中的其他地方进行检查,否则不会检查。(即truckCountballCount不加1)

第二是$('#radioButtons').append(...)在你的每个"循环"中被调用,所以它将为每个与选择器匹配的<img>标签附加那行。