2016-09-05 29 views
2

我正在制作一个网页,其中包含25个可在25个位置点击的按钮。我需要知道是否有更简单的方法来做到这一点,然后我在做什么。也许有些东西会占用更少的线条。按钮被点击,然后计数器被添加到另一个表。在javascript中使用OOP .click功能

$('#one').click(function(){ 
    counter++; 
     $('#ones').text(counter); 

    }); 
    var countertwo = 0; 
    $('#two').click(function(){ 
    countertwo ++; 
    $('#twos').text(countertwo); 
    }); 
+0

我们需要很多关于问题的更多细节我n为了有用的帮助。例如,显示HTML将有助于更清晰地解释“#one”和“#ones”等内容。 –

回答

1

这里猜测的一点,但是:

  • 你可以存储上的按钮本身的计数器。
  • 如果你这样做,并且你给这些按钮一个普通的类(或者其他一些方法来将它们分组),你可以让一个点击处理器处理所有这些。
  • 您或许可以使用结构化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命名约定有关的元素,是最弱位和几乎可以肯定会与有关结构的详细信息更好的做出。

1

您可以使用这样的事情:

<button class="button" data-location="ones">One</button> 
... 
<button class="button" data-location="twenties">Twenty</button> 

<div id="ones" class="location">0</div> 
... 
<div id="twenties" class="location">0</div> 

$('.button').on('click', function() { 
    var locationId = $(this).data('location') 
    , $location = $('#' + locationId); 

    $location.text(parseInt($location.text()) + 1); 
}); 

另请参阅该代码在JsFiddle

+0

这实际上正是我所要查找的,非常感谢您 – Tidesglenn

+0

不客气 –

+1

FWIW,'data'不是'data- *'属性的访问器函数,它可以做到更多或更少。除非你需要'data'功能,否则使用'.attr(“data-location”)。 (也不是在UI中存储数据的粉丝,而不是仅仅让用户界面*反映数据,但这是一个设计调用,而且人们都是双向的。) –

0

自动计数器更干净的解决方案

/* JS */ 
 

 
$(function() { 
 
    var $buttons = $('.withCounter'), 
 
     counters = []; 
 
    
 
    function increaseCounter() { 
 
    var whichCounter = $buttons.index(this)+1; 
 
    counters[whichCounter] = counters[whichCounter] ? counters[whichCounter] += 1 : 1; 
 
    $("#counter"+whichCounter).text(counters[whichCounter]); 
 
    } 
 
    
 
    $buttons.click(increaseCounter); 
 
});
<!-- HTML --> 
 

 
<button class="withCounter">One</button> 
 
<button class="withCounter">Two</button> 
 
<button class="withCounter">Three</button> 
 
<button class="withCounter">Four</button> 
 

 
<p id="counter1">0</p> 
 
<p id="counter2">0</p> 
 
<p id="counter3">0</p> 
 
<p id="counter4">0</p> 
 

 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>