javascript - 如何使用 Javascript +1 onClick

标签 javascript html onclick pre

我需要创建一个数字,d,每次单击

时都会增加1。我已经尝试过 onClick="javascript"和 id="id"但找不到正确的代码,我还需要在 
 上方显示 d 为:“您有 d 个物体!”我将所有 javascript 放在  中,将 html 放在  中(如果这是错误的)。

最佳答案

<span id="counter">0</span>
<pre id="my-pre">test</pre>

<script>
    var counter = 0,
        counterSpan = document.getElementById('counter');

    //add the click listener using addEventListener, this is preferred over inline handlers
    document.getElementById('my-pre').addEventListener('click', function () {
        counterSpan.innerHTML = ++counter;
    });
</script>

但是,将脚本直接放在 HTML 元素后面很快就会变得困惑。更好的选择是模块化您的代码。

//Create an object that represents your feature and encapsulates the logic
var CounterFeature = {
    count: 0,
    init: function (preElSelector, countElSelector) {
        var preEl = this.preEl = document.querySelector(preElSelector);

        this.countEl = document.querySelector(countElSelector);

        preEl.addEventListener('click', this.increment.bind(this));

        return this;
    },
    increment: function () {
        this.countEl.innerHTML = ++this.count;
    }
};

//wait until the DOM is ready and initialize your feature
document.on('DOMContentLoaded', function () {
    //create a new instance of the CounterFeature using Object.create
    //and initialize it calling `init`
    var counterFeature = Object.create(CounterFeature).init('#my-pre', '#counter');

   //you could also simply use the singleton form, if you do not plan to have
   //more than one CounterFeature instance in the page
   //CounterFeature.init(...);
});

关于javascript - 如何使用 Javascript +1 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19756450/

相关文章:

javascript - 在我的网站中保存搜索关键字

html - 如何隐藏:before content in parent by hover on child?

Android:如何在点击不可见按钮时调用函数?

javascript - 具有 Sails.js 后端的 Ionic 应用程序的 $http 身份验证

html - 如何只显示 INPUT 属性中的文本? HTML

javascript - React.js 导入和使用组件

javascript - Plotly.js 点击事件

javascript - 单击事件触发多次(应该是一次)

javascript - javascript中获取内部函数的返回值

javascript - 如果另一个 div 有内容则显示 div