抱歉,标题不好,如果不显示代码,很难解释这一点。
我有一个名为 Coupon 的 javaScript 类,它的功能基本上是打开一个 fancyBox 并显示该优惠券对象的内容(其动态)。
像这样
function CouponPopup( id, title, barcodeUrl, expirationDate, description ) {
this.coupondId = id;
this.couponContainer = document.createElement('div');
this.couponTitle = document.createElement('h2');
this.couponPrizeName = document.createElement('h3');
var self = this;
// More vars, etc. . .
// assemble the coupon
this.couponContainer.appendChild(this.couponTitle);
this.couponContainer.appendChild(this.couponPrizeName);
this.couponContainer.appendChild(this.couponRevealDetails);
this.couponContainer.appendChild(this.couponBarcode);
this.couponContainer.appendChild(this.couponExpirationText);
this.couponContainer.appendChild(this.couponPrintButton);
this.show = function ( event ) {
$.fancybox(self.couponContainer);
}
}; // end class CouponPopup
现在,在调用此函数的代码中,我尝试创建一个链接 - 单击该链接时将调用 CouponPopup 右侧实例上的 show 函数。
for (var i = 0; i < dataLength; i++) {
if (data.type === "coupon") {
var couponId = "coupon_" + i;
// right now, my coupon will be on global scope.
myCoupon = new CouponPopup( couponId,
data.rewards[i].prize_name,
data.rewards[i].url,
data.rewards[i].expirationdate);
rewardInfo = '<a id="' + couponId + '" onclick="myCoupon.show( event )">View Coupon</a>';
}
}
rewardInfo 最终会附加到页面 - 并且看起来不错。
但是,当我单击它时,由于 myCoupon 位于全局范围内 - 显示的 fancyBox 始终是创建的最后一个优惠券。
如果我尝试将 myCoupon 放在本地范围内(添加 var 关键字),我会收到一个 JS 错误,指出 myCoupon 在添加到链接的 onClick 处理程序时未定义。
我想要做的是将 myCoupon 设为局部变量,并且仍然可以正常工作 - 因此链接的 onClick 事件与 myCoupon 的特定实例相关联
执行此操作的最佳方法是什么?我有一个黑客工作,但它是一个黑客,我真的不喜欢需要在我的代码中使用全局变量,如果我可以帮助的话。
在这个问题上有一个脑残,所以感谢任何帮助!
寻找老式的 ES5 解决方案。
最佳答案
您可以尝试执行以下操作:
for (var i = 0; i < dataLength; i++) {
if (data.type === "coupon") {
var couponId = "coupon_" + i;
// right now, my coupon will be on global scope.
myCoupon = new CouponPopup( couponId,
data.rewards[i].prize_name,
data.rewards[i].url,
data.rewards[i].expirationdate);
rewardInfo = '<a id="' + couponId + '" onclick="showCoupon('+ couponId +')">View Coupon</a>';
}
}
然后创建一个如下所示的函数 showCoupon :
function showCoupon (couponId) {
try {
var index = parseInt(couponId.replace('coupon_', ''));
new CouponPopup( couponId,
data.rewards[index].prize_name,
data.rewards[index].url,
data.rewards[index].expirationdate).show();
} catch(err) { console.log("wrong coupon id ", err);}
}
关于JavaScript 作用域 - 在循环中获取 onClick 对象的正确实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726236/