如何阻止多个书签出现?

时间:2011-06-14 17:28:19

标签: javascript bookmarklet

我正在制作一个书签,弹出一个包含各种内容的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>

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);

1 个答案:

答案 0 :(得分:2)

在创建之前,只需检查div是否存在。

var div = document.getElementById("bookmarklet");
if (!div)
{
    div = document.createElement("div");
    div.id = "bookmarklet";
    div.style.margin = "auto";
    div.style.position = "fixed";
}

此外,由于您已经拥有div的全局引用,因此您无需在toggle_bookmarklet中按ID进行搜索。您可以参考div。我会尝试选择一个更独特的名称,以避免遇到命名冲突。

编辑:就此而言,如果您要使用全局变量,则可以进一步简化。甚至不打算给它一个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";
}
相关问题