[英]Javascript variable scope with event handler
This is the nth question about JS variable scope but I read through the rest and didn't quite get an answer. 这是关于JS变量范围的第n个问题,但我通读了其余部分,但并没有完全得到答案。
var notification = window.webkitNotifications.createNotification(
'image.png', // The image.
'New Post: ',// The title.
'New stuff'// The body.
);
var itemLink = 'http://pathtothefile.com';
notification.onclick = function(itemLink) {
window.focus();
window.open(itemLink,'_blank' );
this.cancel();
};
notification.show();
How do i get itemLink, which is defined in the global scope, to work in the onclick function? 我如何获得在全局范围内定义的itemLink在onclick函数中工作?
Remove the parameter from the function: 从函数中删除参数:
notification.onclick = function(itemLink) { // overrides itemLink in the global
// object.
Fixed code: 固定代码:
notification.onclick = function() {
window.focus();
window.open(itemLink,'_blank' );
this.cancel();
};
During name conflicts, local variables take precedence. 在名称冲突期间,局部变量优先。 Remove or rename the argument itemLink
. 删除或重命名自变量itemLink
。
notification.onclick = function(something_else) {
//global itemLink should be accessible
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.