0

每次单击 <pre> 时,我都需要将数字d加 1。我已经尝试过 onClick="javascript" 和 id="id" 但找不到正确的代码,我还需要在 <pre> 上方显示d为:“你有d个对象!” 我把我所有的 javascript 放在 <head> 和我的 html 放在 <body> 如果那是错的。

4

2 回答 2

2
<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(...);
});
于 2013-11-03T19:07:43.113 回答
1

这是我的快速解决方案(js fiddle: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);
}
于 2013-11-03T19:14:57.087 回答