首页 > 解决方案 > 在Javascript中单击复选框时如何获取所有图像URL

问题描述

我只想从 price 和 pic url 的 concat 值中获取图像 url。但是,当我选择具有不同图像的复选框时,它仍然会一直打印第一个选定的图像 url。

当我尝试打印拆分值时,所有价格和图像 url 都显示在 [price,imageurl] 形式的数组中,即 [5,imgurl,7,...] 但是当我尝试打印 res[1] 索引时只有一个即使我从复选框中选择不同的图片,图片网址也会一直出现

 <input name="product" type="checkbox" class="checkbox" id="product" value="<%=price+"&"+photo_url+"&"%>" onclick="totalIt()" />
function totalIt() {  
 var input = document.getElementsByName("product");
  total=0;

 var count=0;
 for (var i = 0; i < input.length; i++) {
   if (input[i].checked) {
     total += parseInt(input[i].value);
     totalpicscost+=input[i].value;
     var f=totalvaluepics.toString();
     res = totalpicscost.split("&");
     count++;
   }

   //console.log("nearestvalue"+res[res.length-1]);
 }
 document.getElementById("pics").value = count;
 document.getElementById("total").value = "Rs " + total.toFixed(2);
 totalvaluepics= [totalpicscost];
  console(res[0]);
 } 

我希望输出打印所有选定的图片 url,而不是在我选择复选框时一直显示的相同图像 url。

标签: javascripthtmlscriptlet

解决方案


理解你的问题并不容易,也不是阅读你的代码,请不要认为它具有冒犯性,但你需要在 JS 样式指南和良好实践上多做一些工作,以摆脱不好的。

关于你的问题(据我所知):

    function totalIt() {

      // Get all inputs
      const inputs = document.querySelectorAll('[name="product"]');

      // Filter out inputs that are checked
      // and map them according to "splitValueIntoPriceAndUrl()" function declared below
      // so the data we need looks like 
      // [{price: 5, imageUrl:'imgurl'}, {price: 7, imageUrl:'imgurl2'}, ...]
      let checkedInputsValues = [ ...inputs ].filter(i => i.checked).map(splitValueIntoPriceAndUrl);

      // as far as I understood from given example,
      // you want to store the count of selected pics in #pics (and why is it an input??)
      document.querySelector('#pics').value = checkedInputsValues.length;

      // and also as far as I understood from given example,
      // you want to store total price into another input#total value,
      // so we reduce our checkedInputsWalues array in a way
      // to calculate all prices together
      const total = checkedInputsValues.reduce((totalPrice, { price }) => totalPrice += price, 0).toFixed(2)
      document.querySelector('#total').value = `Rs ${total}`;

      // and now we are collecting the image urls in res array.
      // now res[] values should be logged (at least).
      const res = checkedInputsValues.map(({ imageUrl }) => imageUrl);
      for (let i = 0; i < res.length; i++) {
        console.log(res[i]);
      }

      // remapper helper
      function splitValueIntoPriceAndUrl(checkbox) {
        return {
          price: parseInt(checkbox.value.split('&')[0]),
          imageUrl: checkbox.value.split('&')[1]
        }
      }

      return res;
    }

关于您的代码风格和实践:

  1. 您已经声明了一些您​​从未使用过的变量:var inputVal = document.getElementById("second");, var f=totalvaluepics.toString();. 不要那样做。
  2. 不要为未声明的变量赋值。
  3. 切换到 ES6 和数组/集合的函数式方法——这很有帮助。

推荐阅读