如何阻止出现多个小书签?
我正在制作一个小书签,它会弹出一个 div,其中包含各种内容...当您单击链接打开小书签两次时,会弹出两个小书签。我该如何防止这种情况发生?
index.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>
代码.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);
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. how do I prevent this from happening?
index.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:
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需在创建之前检查
div
是否存在即可。此外,由于您已经拥有对
div
的全局引用,因此无需在toggle_bookmarklet
中通过 id 搜索它。您只需引用div
即可。不过,我会尝试选择一个更独特的名称,以避免遇到命名冲突。编辑:就此而言,如果您要使用全局变量,则可以进一步简化。甚至不用费心给它一个 id,只需使用全局引用:
Just check for the existence of
div
before creating it.Also, since you already have a global reference to
div
, you don't need to search for it by id intoggle_bookmarklet
. You can just referencediv
. 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: