我制作了一个小应用程序,当点击猫的图片时,会增加计数器。当我使用默认参数设置功能时,它可以工作。但是,当我传递一个字符串来替换函数时,它没有。这两个脚本有什么区别?
第一个脚本,它不会将字符串传递给catClick函数:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick() {
var cat_click_p = document.getElementById("number_clicked");
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick, false);
和脚本的第二个版本,它将字符串传递给catClick函数:
'use strict';
function CatCount (pic_url, cat_name) {
this.pic_url = pic_url;
this.click_count = 0;
this.cat_name = cat_name;
return false;
}
var cat_name;
var pic_url;
var click_count;
function catClick(element_id_to_be_replaced) {
var cat_click_p = document.getElementById(element_id_to_be_replaced);
var number = cat_click_p.innerHTML;
number = parseInt(number) + 1;
cat_click_p.innerHTML = number;
}
var catGrid = document.getElementById('cat_grid');
catGrid.addEventListener('click', catClick('number_clicked'), false);
脚本的第二个版本只增加了一次cat计数器。
此外,这是index.html
文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src='js/app.js'></script>
<title>Cat App</title>
</head>
<body>
<div>
This app keeps track of how many times you click on a cat!
<div class='cat' id='cat_grid'>
<img src='http://thepetproductguru.com/wp-content/uploads/2012/05/CAT-HEADPHONES.jpeg'>
</div>
<div>
This cat has been clicked
<p id='number_clicked'>0</p>
times.
</div>
</body>
</html>
答案 0 :(得分:3)
问题在于以下几行:
catGrid.addEventListener('click', catClick('number_clicked'), false);
在该行中,您正在执行 catClick('number_clicked')
并将该表达式的结果作为第二个参数返回给addEventListener
函数。
两种可能的解决方案是:
//1: Using an anonymous function:
catGrid.addEventListener('click', function() {
catClick('number_clicked')
}, false);
//2: Using bind:
catGrid.addEventListener('click', catClick.bind(this,'number_clicked'), false);