我正在制作一个小书签,弹出一个div,里面有各种各样的东西……当您单击该链接打开该bookmarklet两次时,会弹出两个bookmarklet。如何防止这种情况发生?
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);发布于 2011-06-15 01:34:40
在创建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";
}https://stackoverflow.com/questions/6347552
复制相似问题