点击按钮增加计数 [英] incrementing the count on click of button

查看:146
本文介绍了点击按钮增加计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var index = 0;

通过defualt索引的值为0,现在我有两个按钮,当我点击按钮2或1,索引的值应该增加。点击的第二个按钮应该取值一个......类似的第三个等等。

By defualt the value of index is 0 and now i have two buttons, when i click on button 2 or 1, the value of index should get incremented. the second button on click should take the value one onwards... similarly third etc etc.

推荐答案

你将需要执行此操作的函数:

You're going to need a function to do that:

function incrementIndex() {
    index += 1;
}

这假设你的指数变量是全局的。

This assumes that your index variable is global.

接下来你需要做的是等待点击事件。在JavaScript中有三种方法可以做到这一点。

Next what you'll need to do is wait for the click event. There are three ways to do that in JavaScript.


  1. 内联JavaScript

<button onclick="incrementIndex()">Button 1</button>
<button onclick="incrementIndex()">Button 2</button>

这就是希特勒开发网站的方式。不要这样做。

This is how Hitler developed websites. Don't do this.

事件处理程序

这需要你要等到DOM加载完毕,然后以某种方式获取你的两个按钮。如果页面上只有两个按钮,则可以执行以下操作(但仅当此脚本在文档中的HTML之后>时):

This requires you to wait until the DOM has loaded, and then "get" your two buttons somehow. If you only have two buttons on the page, you can do something like this (but only if this script comes after the HTML in your document):

var buttons = document.getElementsByTagName('button');
buttons[0].onclick = buttons[1].onclick = incrementIndex;

请注意,该示例中有括号() incrementIndex 结束时。

Note in that example that there are no parentheses () at the end of incrementIndex.

事件监听器

事件处理程序的问题是您一次只能附加一个函数。如果你要让其他JavaScript监听按钮点击,你将不得不使用事件监听器。

The problem with event handlers is that you can only attach one function at a time. If you're going to have other JavaScript listening for button clicks, you'll have to use event listeners.

但事件监听器是一个主要的痛苦,因为IE6 -8做错了,并且(取决于项目)你可能需要围绕它进行编码。最简单的方法是,如何在大多数浏览器中添加事件监听器:

But event listeners are a major pain in the butt because IE6-8 does it wrong, and (depending on the project) you'll probably have to code around it. At it's simplest, here's how to add an event listener in most browsers:

var addEvent = window.addEventListener ? function (elem, type, method) {
    elem.addEventListener(type, method, false);
} : function (elem, type, method) {
    elem.attachEvent('on' + type, method);
};

addEvent(buttons[0], 'click', incrementIndex);
addEvent(buttons[1], 'click', incrementIndex);

这只是跨浏览器事件监听的表面。如果您想了解更多信息,请 QuirksMode上有很多文章

That is just the surface of cross-browser event listening. If you want to learn more, QuirksMode has a good series of articles on it.

这篇关于点击按钮增加计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆