使用for循环与Chrome通知导致错误的onclick链接

Using a for loop with Chrome Notifications results in wrong onclick link

本文关键字:错误 onclick 链接 通知 for 循环 Chrome 使用      更新时间:2023-09-26

我一直在编写一个Javascript文件,该文件调用for循环,并在循环的每次迭代中以编程方式创建一个新链接,该链接通过浏览器推送通知推送给用户。这些唯一的链接也作为onclick事件附加到通知中。我运行代码并尝试点击通知,但我发现,而不是每个通知都有自己独特的onclick链接,所有连续的通知都采取了最近通知的onclick。

我在这里包含了一个演示我所面临的问题的基本代码:https://jsbin.com/loyeviguqu/1/edit?html,js,output

*编辑:对不起,我很快意识到我链接到错误的jsbin,正确的链接现在更新

从我编写的代码中,您将看到我用for循环创建了3个链接google.com/0, google.com/1, google.com/2。此外,在每次迭代的for循环中,我将链接作为onclick事件附加到通知中。然而,你会发现点击这三个通知中的任何一个都会显示google.com/2,,而不是其他两个。然而,通知中的文本保持其独特性。

我目前的怀疑是每次我附加一个onclick通知它覆盖旧的,但我在如何解决这个问题的损失。

对这个问题的任何解释或见解都将非常感激!谢谢!

// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
});
function notifyMe() {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); 
    return;
  }
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
        var string = "http://google.com/" + 1;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });
    notification.onclick = function () {
      window.open(this.title);      
    };
     var string = "http://google.com/" + 2;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });
    notification.onclick = function () {
      window.open(this.title);      
    };
     var string = "http://google.com/" + 3;
    var notification = new Notification(string, {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "I should be linking to " + string ,
    });
    notification.onclick = function () {
      window.open(this.title);      
    };
  }
}