javascript - 尝试附加特定图像类型的图像计数 | jQuery

标签 javascript jquery html

我希望此功能在用户点击时打印球图片的数量或消防车图片的数量:

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.");
}

关于javascript - 尝试附加特定图像类型的图像计数 | jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096017/

相关文章:

javascript - 即使值没有改变也会触发 onChange

javascript - 使用 jQuery 在 HTML 表中将切换元素设置为 'on' 或 'off' 给定值

javascript - 选择一个选项后,如何使此下拉菜单不自行关闭

html - 将行内 block 左对齐

javascript - ReactJS setState 更改不会从父组件传播到子组件

javascript - jQuery 无法从 PHP 文件读取 JSON

html - 打开 DevTools 时,Electron BrowserWindow 切换到暗模式

html - 如何在其他两个 html 元素之间的公共(public)边界上显示一个 html 元素?

javascript - RESTful Web 应用程序中的客户端服务器架构

jQuery 使用一个 .js 文件实现不同页面的不同操作