在javascript中使用OOP on.click函数
我正在做一个网页,有一个棒球罢工与25个按钮,将在25个地点点击之一。我需要知道是否有一个更简单的方法来做到这一点,然后我在做什么。也许有些东西会占用更少的线路。单击按钮,然后计数器被一个添加到另一个表中在javascript中使用OOP on.click函数,javascript,jquery,Javascript,Jquery,我正在做一个网页,有一个棒球罢工与25个按钮,将在25个地点点击之一。我需要知道是否有一个更简单的方法来做到这一点,然后我在做什么。也许有些东西会占用更少的线路。单击按钮,然后计数器被一个添加到另一个表中 $('#one').click(function(){ counter++; $('#ones').text(counter); }); var countertwo = 0; $('#two').click(function(){
$('#one').click(function(){
counter++;
$('#ones').text(counter);
});
var countertwo = 0;
$('#two').click(function(){
countertwo ++;
$('#twos').text(countertwo);
});
这里有点猜测,但是:
- 您可以将计数器存储在按钮本身上
- 如果您这样做了,并且为按钮提供了一个公共类(或者以其他方式对它们进行分组),则可以使用一键式处理程序处理所有按钮
- 您可能可以使用结构化CSS查询而不是
值找到正在更新的其他元素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命名约定将元素关联起来,这是最薄弱的一点,几乎可以肯定的是,如果有更多关于您的结构的信息,它会变得更好。您可以使用以下内容:
<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);
});
1
...
二十
0
...
0
$('.button')。在('click',function()上{
var locationId=$(this).data('location')的值
,$location=$(“#”+locationId);
$location.text(parseInt($location.text())+1);
});
另请参见带有自动计数器的更清洁溶液上的此代码
/*JS*/
$(函数(){
变量$buttons=$('.withCounter'),
计数器=[];
函数递增计数器(){
var whichCounter=$buttons.index(this)+1;
计数器[whichCounter]=计数器[whichCounter]?计数器[whichCounter]+=1:1;
$(“#计数器”+whichCounter).text(计数器[whichCounter]);
}
$按钮。单击(递增计数器);
});代码>
一个
两个
三
四
0
0
0
0
我们需要更多关于该问题的详细信息,以便提供有用的帮助。例如,显示HTML将有助于更清楚地解释什么是#one
和#one
等等。这正是我想要的。非常感谢大家,数据
不是数据-*
属性的访问器函数,它做的更多和更少。除非您需要数据
功能,否则请改用.attr(“数据位置”)
。(也不喜欢在UI中存储数据,而不仅仅是让UI反映数据,但这是一个设计调用,人们会双向选择。)您可以使用.attr('data-location')
或.data('location')
,它们都可以工作。但我同意你的看法,.attr
是更可取的方式。