[英]How do I stop multiple bookmarklets from appearing?
I am in the process of making a bookmarklet that pops up a div with various things in it... when you click on the link to open the bookmarklet twice, two bookmarklets pop up.我正在制作一个小书签,它会弹出一个包含各种内容的 div……当您单击链接两次打开小书签时,会弹出两个小书签。 how do I prevent this from happening?
我该如何防止这种情况发生?
index.html:索引.html:
<html>
<head>
<title>Bookmarklet Home Page</title>
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
<a href="javascript:(function(){code=document.createElement('SCRIPT');code.type='text/javascript';code.src='code.js';document.getElementsByTagName('head')[0].appendChild(code)})();">click here</a>
</body>
</html>
code.js:代码.js:
function toggle_bookmarklet() {
bookmarklet = document.getElementById("bookmarklet");
if (bookmarklet.style.display == "none") {
bookmarklet.style.display = "";
}
else {
bookmarklet.style.display = "none";
}
}
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
content = "";
content += "<a href='javascript:void(0);'><div id='xbutton' onClick='javascript:toggle_bookmarklet();'>x</div></a>";
div.innerHTML = content;
document.body.appendChild(div);
Just check for the existence of div
before creating it.只需在创建之前检查
div
是否存在。
var div = document.getElementById("bookmarklet");
if (!div)
{
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
}
Also, since you already have a global reference to div
, you don't need to search for it by id in toggle_bookmarklet
.此外,由于您已经拥有对
div
的全局引用,因此您无需在toggle_bookmarklet
中通过 id 搜索它。 You can just reference div
.你可以参考
div
。 I'd try to choose a more unique name though, so as to avoid running in to naming collisions.不过,我会尝试选择一个更独特的名称,以避免遇到命名冲突。
Edit: For that matter, if you are going to use a global variable, you can simplify further.编辑:就此而言,如果您要使用全局变量,则可以进一步简化。 Don't even bother giving it an id, just use the global reference:
甚至不用给它一个 id,只需使用全局引用:
function toggle_bookmarklet() {
bookmarkletEl.style.display = bookmarkletEl.style.display == "none" ? "" : "none";
}
if (!window.bookmarkletEl) {
var bookmarkletEl = ddocument.createElement("div");
bookmarkletEl.style.margin = "auto";
bookmarkletEl.style.position = "fixed";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.