javascript - 在 javascript 中的 .click 函数上使用 OOP

标签 javascript jquery

我正在制作一个网页,其中有一个棒球击球区,其中有 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/

相关文章:

jquery - 语法错误 : expected expression, 得到 '<' - Jquery 1.10.2

javascript - 为每个 id 创建一个独特的 jquery 对话框样式

javascript - 努力让悬停的第 n 个 child 在 IE 中工作

javascript - 生成 HTML 表单

javascript - 如何在网站不闪烁/重新加载的情况下在 React 中动态注入(inject)样式表?

javascript - 在过滤器返回 Pandoc-filter 上返回两个元素

javascript - data.forEach 不是一个函数

向上滚动或向下滚动时的 JavaScript 事件

javascript - 获取特定表单的所有元素

javascript - 将变量作为 HREF