我需要创建一个数字,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/