如何阻止多个小书签出现?

| 我正在制作一个使其中包含各种内容的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);
    
已邀请:
        只需在创建前检查
div
的存在。
var div = document.getElementById(\"bookmarklet\");
if (!div)
{
    div = document.createElement(\"div\");
    div.id = \"bookmarklet\";
    div.style.margin = \"auto\";
    div.style.position = \"fixed\";
}
另外,由于您已经对
div
进行了全局引用,因此无需在by5ѭ中按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\";
}
    

要回复问题请先登录注册