counter만들기

dadumvu·2020년 4월 21일
0

인터뷰 기출

목록 보기
1/1
post-thumbnail

There is a button on a page with text inside that says 'Clicked {#} times' with the number changing each time the button has been clicked.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>You cannot add a new property to a constructor function.</p>

<p id="demo"></p>
<div class="btn">button</div>
<script>
var count = 0

document.addEventListener('click', function(e){
	e.preventDefault()
	count += 1
	document.getElementById("demo").innerHTML = count
}, false)

</script>
<style>
.btn {
	width: 100px;
    height: 100px;
    background-color: red;
}
</style>
</body>
</html>

Follow up: Now each time the button is clicked, spawn a new button with its own counter, and the same functionality.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>You cannot add a new property to a constructor function.</p>

<p id="demo"></p>
<p id="demo2"></p>
<input type='button' value='button' id='target'>
<input type='button' value='button' id='target2'>
<script>
class Counter {
	constructor(){
    	this.count = 0
    }
    increase() {
    	this.count++
    }
}

var counter1 = new Counter()
var counter2 = new Counter()

var c1 = document.getElementById('target')
c1.addEventListener('click', btn_listener)
var c2 = document.getElementById('target2')

c2.addEventListener('click', btn_listener)

function btn_listener(e){
    e.preventDefault()
    switch(e.target.id) {
    	case 'target':
        	counter1.increase()
            var c1_count = document.getElementById('demo')
            c1_count.innerHTML = counter1.count
            break
        case 'target2': 
        	counter2.increase()
	        var c2_count = document.getElementById('demo2')
    	    c2_count.innerHTML = counter2.count
            break
   }
}


</script>
<style>
.btn {
	width: 100px;
    height: 100px;
    background-color: red;
}
</style>
</body>
</html>

0개의 댓글