簡體   English   中英

如何使用 Javascript +1 onClick

[英]How can +1 onClick with Javascript

, increase by 1 every time I click a <pre>.每次單擊 <pre> 時,我都需要使數字增加 1。 above the <pre> as: "You have objects!"我試過 onClick="javascript" 和 id="id" 但找不到正確的代碼,我還需要在 <pre> 上方顯示為:“你有對象!” 我把我所有的 javascript 放在 <head> 中,把我的 html 放在 <body> 中,如果那是錯的。

<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(...);
});

這是我的快速解決方案(js小提琴: http : //jsfiddle.net/65TMM/

使用 html:

<pre>Add another object</pre>
<p>You have <span class="count">0</span> objects!</p>

和 javascript(使用 jQuery):

$(function() {

    $('pre').on("click", function() {
        addOneToObjects();
    })

});

function addOneToObjects() {
    var countSpan = $('.count');
    var currentThings = parseInt( countSpan.text() );
    currentThings++;
    countSpan.text(currentThings);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM