0

使用greasemonkey 添加这两个按钮。我试过颠倒顺序,它总是第二个添加的按钮有效。另一个按钮不会触发 onclick 事件。

// Add the click to chat button
mydiv             = document.getElementById("optionalJobinfoData");
var btn           = document.createElement("input");
btn.type          = 'button';
btn.value         = 'Click to Chat';
btn.onclick       = function() { window.open(chatURL); };
mydiv.innerHTML  += "<i>Notify Dispatch</i><br><i>(stuck on job)</i>&nbsp;&nbsp;";
mydiv.appendChild(btn);

// Credentials button
mydiv             = document.getElementById("optionalJobinfoData");
btn               = document.createElement("input");
btn.type          = 'button';
btn.value         = 'Credentials';
btn.onclick       = function() { window.open(credsURL); };
mydiv.innerHTML  += "<br><br><i>DSL Credentials</i> ";
mydiv.appendChild(btn);
4

3 回答 3

2

问题在于做 mydiv.innerHTML += ...

它类似于这里的答案。 操作innerHTML 会移除子元素的事件处理程序?

于 2013-02-08T18:24:52.107 回答
1
// Add the click to chat button
mydiv             = document.getElementById("optionalJobinfoData");
var btn           = document.createElement("input");
btn.type          = 'button';
btn.id            = 'openChat';
btn.value         = 'Click to Chat';
mydiv.innerHTML  += "<i>Notify Dispatch</i><br><i>(stuck on job)</i>&nbsp;&nbsp;";
mydiv.appendChild(btn);

// Credentials button
mydiv             = document.getElementById("optionalJobinfoData");
btn               = document.createElement("input");
btn.type          = 'button';
btn.value         = 'Credentials';
btn.id            = 'openCreds';
mydiv.innerHTML  += "<br><br><i>DSL Credentials</i> ";
mydiv.appendChild(btn);

document.getElementById("openCreds").onclick = function() { window.open(credsURL); };
document.getElementById("openChat").onclick = function() { window.open(chatURL); };

以上应该可以正常工作。问题是innerHTML +=基本上重新创建对象。并且指向 onclick 函数处理程序的指针因此丢失(类型、值等是 HTML 的一部分,但 innerHTML 无法获取指向 onclick 函数的指针)

于 2013-02-08T18:26:14.630 回答
1

以下行导致问题:

mydiv.innerHTML  += "<br><br><i>DSL Credentials</i> ";

这和这样做是一样的:

var oldHTML = mydiv.innerHTML;
var newHTML = oldHTML + "<br><br><i>DSL Credentials</i> ";

// This destroys everything inside the div and re-creates it based on the innerHTML.
mydiv.innerHTML = newHTML;

它基本上是破坏 div 内的任何元素并根据 html 源代码重新创建它们。但是,onclick 代码不包含在 innerHTML 中。

于 2013-02-08T18:37:58.883 回答