使用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> ";
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);
答案 0 :(得分:2)
问题在于做mydiv.innerHTML + = ...
这与答案类似。 Manipulating innerHTML removes the event handler of a child element?
答案 1 :(得分: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> ";
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函数的指针)
答案 2 :(得分: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中。