我正在制作一个网页,其中有一个棒球击球区,其中有 25 个按钮,可在 25 个位置单击。我需要知道是否有比我正在做的更简单的方法来做到这一点。也许会占用更少的线路。单击该按钮,然后将计数器添加到另一个表中。
$('#one').click(function(){
counter++;
$('#ones').text(counter);
});
var countertwo = 0;
$('#two').click(function(){
countertwo ++;
$('#twos').text(countertwo);
});
最佳答案
这里有一点猜测,但是:
- 您可以将计数器存储在按钮本身上。
- 如果您这样做,并且为按钮指定了一个公共(public)类(或以其他方式对它们进行分组),则可以让一次点击处理程序处理所有按钮。
- 您可能可以使用结构化 CSS 查询而不是
id
值找到要更新的其他元素。
但依赖于这些 ID 值:
$(".the-common-class").click(function() {
// Get a jQuery wrapper for this element.
var $this = $(this);
// Get its counter, if it has one, or 0 if it doesn't, and add one to it
var counter = ($this.data("counter") || 0) + 1;
// Store the result
$this.data("counter", counter);
// Show that in the other element, basing the ID of what we look for
// on this element's ID plus "s"
$("#" + this.id + "s").text(counter);
});
最后一点,即通过 ID 命名约定关联元素,是最薄弱的一点,并且几乎可以肯定,通过有关结构的更多信息可以做得更好。
关于javascript - 在 javascript 中的 .click 函数上使用 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335078/