简体   繁体   English

数组索引链接到事件侦听器循环

[英]Array index link to event listener loop

I'm trying to simplify / re-factor price calculation for multiple products.我正在尝试简化/重新考虑多种产品的价格计算。

Code demo: https://jsfiddle.net/helloKittychan/jLfwgsz6/2/代码演示: https : //jsfiddle.net/helloKittychan/jLfwgsz6/2/

Structure:结构:

  • Prices: stored in an array as [0] [1].价格:作为 [0] [1] 存储在数组中。

  • Quantity: user input integer for each product.数量:每个产品的用户输入整数。

  • Subtotal calculation: on 'blur' (user input) * (corresponding array[n]).小计计算:在'blur'(用户输入)*(对应数组[n])上。

Problem问题

The first product Candy1 works fine up to calculating sub total as I hard-coded variables.第一个产品 Candy1 可以很好地计算小计,因为我对变量进行了硬编码。 Then I embarked upon re-factoring the code using 'blur' event listener loop for quantity input fields for Candy1 & Candy 2. The event listener works fine on the quantity field, but now I'm stuck on how to call the corresponding price value for the current event.然后我开始使用“blur”事件侦听器循环为 Candy1 和 Candy 2 的数量输入字段重新分解代码。事件侦听器在数量字段上工作正常,但现在我被困在如何调用相应的价格值上对于当前事件。 I guess either calling directly from array or calling from HTML element is possible, but I couldn't figure out the logic to pinpoint to the right price corresponding to the current event, or not sure if that's possible.我想直接从数组调用或从 HTML 元素调用都是可能的,但我无法找出与当前事件相对应的正确价格的逻辑,或者不确定这是否可能。

Previous research以前的研究

I've looked around some posts & pages, but none of them seem simple enough nor similar enough for me to synthesise into my code.我环顾了一些帖子和页面,但没有一个看起来足够简单,也不够相似,无法合成到我的代码中。

  • The visible effect of this is similar to (I think) what I want, but the logic is not.这的可见效果类似于(我认为)我想要的,但逻辑不是。 Accessing child array by index and updating view when index increments (SO post)通过索引访问子数组并在索引增加时更新视图(SO post)

  • Logically similar but the HTML structure is different: Get value from select list in JS (SO post)逻辑相似但 HTML 结构不同: Get value from select list in JS (SO post)

  • I looked at the section [Arrays and Loops] at the bottom of the page, but I couldn't work it out how to make use of it.我查看了页面底部的 [Arrays and Loops] 部分,但我无法弄清楚如何使用它。 Javascript Arrays (by Home and Learn website) Javascript 数组(来自 Home and Learn 网站)

  • Stack Overflow search keywords js array select index Stack Overflow 搜索关键字 js 数组选择索引

Questions问题

  1. Given that I'm a novice, is my attempt to re-factor too ambitious?鉴于我是新手,我的重构尝试是否过于雄心勃勃?
  2. Or can you suggest a simple solution / point me to relevant ref?或者您能否提出一个简单的解决方案/将我指向相关参考? (Prefer pure js, no libraries if possible) (首选纯 js,如果可能,不要使用库)

I also suspect my HTML design is inefficient.我也怀疑我的 HTML 设计效率低下。 Any suggestions to make my little project work will be much appreciated.任何使我的小项目工作的建议将不胜感激。

Code demo: https://jsfiddle.net/helloKittychan/jLfwgsz6/2/代码演示: https : //jsfiddle.net/helloKittychan/jLfwgsz6/2/

Js only:仅JS:

// Inserting prod prices
var prodPrices = ["0.33", "0.50"];
document.getElementById("prod1").innerHTML = "£ " + prodPrices[0];
document.getElementById("prod2").innerHTML = "£ " + prodPrices[1];

// Setting up a universal Event Listener
document.addEventListener("DOMContentLoaded", 
function() { 

// grabbing (=var) the common Class name within the target block.
var qtyInput =
document.getElementsByClassName("qty-input");

// event listener = counting the number of grabbed Class occurrence (=array) 
// and listening to a defined event (click/blur etc) on them + define event name.
for(var i = 0; i < qtyInput.length; ++i) {
qtyInput[i].addEventListener("blur", gotQty);

}

// Function to identify current element with event.
function gotQty(event) {
var qtyId = this.value;
var bow = qtyId * prodPrices[0];
console.log(qtyId); 
console.log(bow);   
}
});

// Calculating subtotal (qty * price) - currently only works for "Candy 1".
function subTot() {
var prod1Qty = document.getElementById("qtyFlat1").value; //this
var subTotProd1 = prod1Qty * prodPrices[0];
var subTotClean = subTotProd1.toFixed(2);
        document.getElementById("prod1-subtotal").innerHTML = subTotClean;
// condescending health warning
if (prod1Qty > 10 ) {
    document.getElementById("quantity-alert").innerHTML = "Too much sugar is bad for you.<br>Select between 1 ~ 10.";
    return false;
}else{
        return true;
}
}
subTot();
// Clearing invalid data & error message then resetting the sub tot - currently only works for "Candy 1".
function clearSub() {
var prod1QtyOver = document.getElementById("qtyFlat1").value;
if(prod1QtyOver > 10){
    document.getElementById("quantity-alert").innerHTML = "<br><br>";
    document.getElementById("qtyFlat1").value = "";
    document.getElementById("prod1-subtotal").innerHTML = prodPrices[0];
}
}
clearSub();

If I were generating the fields dynamically I would use the data- attribute and set the attribute to be the values of the items.如果我动态生成字段,我将使用data-属性并将该属性设置为项目的值。 This can then be accessed by the JS when the user clicks out of the field.当用户点击该字段时,JS 可以访问它。

For example: in the fields, add another attribute data-price which is set to the items prices respectively (this involves some DOM manipulation).例如:在字段中,添加另一个属性data-price分别设置为商品价格(这涉及一些 DOM 操作)。

...
<input class="qty-input" data-price="0.33" id="qtyFlat1" type="text" placeholder="1" class="qty" style="width: 30px;" maxlength="4" onblur="subTot()" onclick="clearSub()" onkeypress=""/>
...
<input class="qty-input" data-price="0.5" id="qtyFlat2" type="text" placeholder="1" class="qty" style="width: 30px;" maxlength="4" onblur="subTot()" onclick="clearSub()" onkeypress=""/>
...

In the javascript:在javascript中:

function gotQty(event) {
  var qtyId = this.value;
  var bow = qtyId * Number(event.srcElement.dataset.price);
  console.log(qtyId);   
  console.log(bow);
}

See http://jsfiddle.net/boo261cc/3 and open up your console.请参阅http://jsfiddle.net/boo261cc/3并打开您的控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM