Javascript & HTML - 计算按钮被点击的次数

Javascript & HTML - count number of times button is clicked

所以我在库存中的每个项目旁边都有一个 'add' 按钮,我正在尝试弄清楚如何操作该按钮以使其用作计数器。我的问题是这些按钮是在 javascript 文件中声明的,因此 HTML 文件中没有按钮 ID 可用于我的 buttonClicked() 函数,该函数基本上应该计算任何次数'add' 按钮一共被点击。

例如,我的页面现在看起来像这样:

笔记本电脑

iMac 2000 美元 [添加按钮]

戴尔 600 美元 [添加按钮]

计算机

Windows PC $1300 [添加按钮]

如果我单击 iMac 旁边的按钮和 Windows PC 旁边的按钮,那么 buttonClicked() 函数应该打印 "You clicked the button 2 times." 我只是在尝试访问javascript 文件中“newContent += <input type=button value="Add" onclick="add(this)"/>”行而不是 HTML 文件中定义的按钮变量。 HTML 文件中定义的那个按钮是一个 select 按钮,与我尝试访问的按钮不同。任何帮助将不胜感激。

let count;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}


function buttonClicked() {
  count++;
  let div = document.getElementById("list");
  div.innerHTML = "You clicked the button " + count + " times.";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim())
}


let electronics = {
 store: "Mike's Computers",
 inventory: {
  "Laptops": {
   0: {
    brand: "iMac",
    cost: 2000
   },
   1: { 
    brand: "Dell",
    cost: 600
   }
  },
  "Computers": {
   2: {
    brand: "Windows PC",
    cost: 1300
   }
  }
 }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a store</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
  </form>

</div>
<div id="div"></div>

你没有为 count 输入初始值 让计数 = 0;

并且必须在每次 单击添加按钮时调用 buttonClicked()

let count = 0;

function init() {
  count = 0;
  let button = document.getElementById("but");
  button.onclick = buttonClicked;
}


function buttonClicked() {
  count++;
  let div = document.getElementById("coutner");
  div.innerHTML = "You clicked the button " + count + " times.";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach(key => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(add) {
  console.clear();
  console.log(add.closest('div').textContent.trim());
  buttonClicked();
}


let electronics = {
  store: "Mike's Computers",
  inventory: {
    "Laptops": {
      0: {
        brand: "iMac",
        cost: 2000
      },
      1: {
        brand: "Dell",
        cost: 600
      }
    },
    "Computers": {
      2: {
        brand: "Windows PC",
        cost: 1300
      }
    }
  }
};
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
      <option value="none">Select a restaurant</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" onclick="showOptions(); buttonClicked()" />
    <div><mark id="coutner"></mark></div>
  </form>

</div>
<div id="div"></div>

像这样?

  • 将计数初始化为 0
  • 向 select 添加事件侦听器 - 从 select
  • 移除点击
  • 使用委托将事件监听器添加到未来的按钮
  • 为消息使用单独的div

let count=0;

let electronics = { store: "Mike's Computers", inventory: {  "Laptops": {   0: {    brand: "iMac",    cost: 2000   },   1: {     brand: "Dell",    cost: 600   }  },  "Computers": {   2: {    brand: "Windows PC",    cost: 1300   }  } }};


window.addEventListener("load", function() {
  count = 0;
  document.getElementById("list").addEventListener("change", function() {
    showOptions(this);
  })
  
  document.getElementById("div").addEventListener("click", function(e) {
    const tgt = e.target;
    if (tgt.type==="button") {
      add(tgt)
    }
  })
})


function buttonClicked() {
  count++;
  let div = document.getElementById("msg");
  div.innerHTML = "You clicked the button " + count + " time"+(count===1?"":"s")+".";
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  div.innerHTML = "";
  if (userPicked === 'none') return;
  var newContent = (electronics.store);
  newContent += '<div>';
  Object.keys(electronics.inventory).forEach(key => {
    newContent += key;
    newContent += '<div>';
    var items = Object.values(electronics.inventory[key]);
    items.forEach(item => {
      newContent += '<div>';
      newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
      newContent += `<input type=button value="Add""/>`
      newContent += '</div>';
    });
    newContent += '</div>';
  });
  newContent += '</div>';
  div.innerHTML = newContent;

}

function add(add) {
  buttonClicked()
  console.clear();
  console.log(add.closest('div').textContent.trim())
}
<div>
  <h1>Welcome</h1>
</div><br />
<div class="dropdown">
  <form>
    <select name="list" id="list" accesskey="target">
      <option value="none">Select a store</option>
      <option value="Electronics">Electronics</option>
    </select>
    <input type=button id="but" value="Select" />
  </form>

</div>
<div id="div"></div>
<div id="msg"></div>

您没有选择正确的按钮 ID。 如果您想在单击每个相邻按钮后更新按钮值,那么这里是代码。

function buttonClicked(id, c) {
  c++;
  document.getElementById(id).value = c;
}

function showOptions(el) {
  let userPicked = el.value;
  var div = document.getElementById("div");
  if (userPicked != 'none') {
    var newContent = (electronics.store);
    newContent += '<div>';
    Object.keys(electronics.inventory).forEach((key) => {
      newContent += key;
      newContent += '<div>';
      var items = Object.values(electronics.inventory[key]);
      items.forEach(item => {
        newContent += '<div>';
        newContent += `&nbsp; <span class="brand"> ${item.brand} </span>  <span class="price">$${item.cost}</span>`;
        newContent += `<input type=button id=${item.id} value="Add" onclick="add(this)"/>`
        newContent += '</div>';
      });
      newContent += '</div>';
    });
    newContent += '</div>';
    div.innerHTML = newContent;
  }
}

function add(e) {
  let id = e.attributes[1].value;
  let val = e.attributes[2].value;
  if(val == 'Add'){
    buttonClicked(id, 0)
  } else {
    buttonClicked(id, val);
  }
}


let electronics = {
    store: "Mike's Computers",
    inventory: {
        "Laptops": {
            0: {
        id: 1,
                brand: "iMac",
                cost: 2000
            },
            1: { 
        id: 2,
                brand: "Dell",
                cost: 600
            }
        },
        "Computers": {
            2: {
        id:3,
                brand: "Windows PC",
                cost: 1300
            }
        }
    }
};
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <div><h1>Welcome</h1></div><br />
<div class="dropdown">
    <form>
    <select name="list" id="list" accesskey="target" onchange="showOptions(this); buttonClicked(this)">
        <option value="none">Select a restaurant</option>
        <option value="Electronics">Electronics</option> 
    </select>
    <input type=button id = "but" value="Select" onclick="showOptions(); buttonClicked()" />
    </form>

</div>