【问题标题】:Javascript & HTML - count number of times button is clickedJavascript & HTML - 计算按钮被点击的次数
【发布时间】:2020-05-16 20:39:27
【问题描述】:

所以我在库存中的每个项目旁边都有一个“添加”按钮,我试图弄清楚如何操作该按钮,以便它可以用作计数器。我的问题是这些按钮是在 javascript 文件中声明的,因此 HTML 文件中没有按钮 id 可用于我的 buttonClicked() 函数,该函数基本上应该计算任何“添加”按钮的总点击次数.

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

笔记本电脑

iMac 2000 美元 [添加按钮]

戴尔 600 美元 [添加按钮]

电脑

Windows PC 1300 美元 [添加按钮]

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

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>

【问题讨论】:

  • 我建议您将点击委托给&lt;div id="div",而不是在按钮上使用内联脚本
  • 你是反对 jQuery 还是只想要一个 javascript 的答案?
  • showOptions 方法中的电子变量从何而来?如果不初始化,很明显你会收到错误..
  • 我可以使用 css、javascript 和 html。遗憾的是没有其他程序。
  • 我用相关的电子变量/项目更新了它。

标签: javascript html button onclick onchange


【解决方案1】:

您没有选择正确的按钮 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>

【讨论】:

    【解决方案2】:

    像这样?

    • 将计数初始化为 0
    • 向选择添加事件侦听器 - 从选择中移除点击
    • 使用委托将事件监听器添加到未来的按钮
    • 为消息使用单独的 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>

    【讨论】:

      【解决方案3】:

      您没有为 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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-06
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        • 2020-05-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多