简体   繁体   English

如何使 onClick 应用于数字表单的标签?

[英]How can I make onClick apply to the label of a number form?

I have a page where with about 100 number forms.我有一个页面,其中包含大约 100 个数字表格。 Each form has a different label, name, id, etc. This is to apply some other javascript later on.每个表单都有不同的标签、名称、id 等。这是为了稍后应用其他一些 javascript。

Two questions: Is it possible to rig the javascript so the number form increases by one when clicking on the label (ie. click on "Apples") rather than the number box?两个问题:是否可以绑定 javascript,以便在单击标签(即单击“Apples”)而不是数字框时数字形式增加 1? And since every form has a different id, is it possible to grab each form by something other than its id (an alternate catch-all so it can easily be applied to around 100 different forms)?并且由于每个表单都有不同的 id,是否可以通过其 id 以外的其他东西来获取每个表单(一个替代的包罗万象,所以它可以很容易地应用于大约 100 个不同的表单)?

Thank you in advance!先感谢您!

<html lang="en">
<head>
<script>
    var i = 0;
    function onClick() {
        document.getElementById('applesQuantity').value = ++i;
    }
</script>
</head>
<body>
</body>

<label>Apples </label><input type="number" name="apples-quantity" id="applesQuantity" onclick="onClick()">
<label>Oranges </label><input type="number" name="oranges" id="orangesQuantity" onclick="onClick()">

</html>

I'd use event delegation - watch for clicks on a <label> , and when seen, navigate to the element's nextElementSibling to get to the input, and increment it:我会使用事件委托 - 观察<label>上的点击,当看到时,导航到元素的nextElementSibling以获取输入,并增加它:

 document.body.addEventListener('click', (e) => { if (e.target.matches('label')) { const input = e.target.nextElementSibling; input.value = 1 + Number(input.value); } });
 <label>Apples </label><input type="number" name="apples-quantity" id="applesQuantity": > <label>Oranges </label><input type="number" name="oranges" id="orangesQuantity": >

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

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