有onclick打印时也可以点击密码提示

时间:2016-01-22 04:36:27

标签: javascript jquery html

我有一个问题,我有一个打印按钮按钮我想在打印窗口弹出之前提示/提示密码

这是我的jsfiddle http://jsfiddle.net/95ezN/884/

document.getElementById("btnPrint").onclick = function () {
printElement(document.getElementById("printThis"));
 }

function printElement(elem) {
var domClone = elem.cloneNode(true);

var $printSection = document.getElementById("printSection");

if (!$printSection) {
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    document.body.appendChild($printSection);
}

$printSection.innerHTML = "";
$printSection.appendChild(domClone);
window.print();
}

我可以打开提示但我想要输入类型密码然后我想要打开打印窗口

请帮忙

2 个答案:

答案 0 :(得分:1)

像这样更改脚本:

document.getElementById("btnPrint").onclick = function () {
var password;

    var pass1="cool";

password=prompt('Please enter your password to view this page!',' ');

if (password==pass1)
{ 
  printElement(document.getElementById("printThis"));
} //Close if here
} // Close your btnPrint click function here

function printElement(elem) {
var domClone = elem.cloneNode(true);

var $printSection = document.getElementById("printSection");

if (!$printSection) {
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    document.body.appendChild($printSection);
}

$printSection.innerHTML = "";
$printSection.appendChild(domClone);
window.print();
}

以下是更新后的Fiddle

答案 1 :(得分:0)

存在逻辑错误。

说明:

/* $printSection is declared */
var $printSection = document.getElementById("printSection");
/* if $printSection isnt exists.. */
if (!$printSection) {
    /* ERROR : make new local variable that named as $printSection*/
    var $printSection = document.createElement("div");
    $printSection.id = "printSection";
    document.body.appendChild($printSection);
}
/* this code is the same as null.appendChild(domClone) */
$printSection.appendChild(domClone);

所以这段代码应该像

var $printSection = document.getElementById("printSection");
if (!$printSection) {
    /* like this*/
    $printSection = document.createElement("div");
    $printSection.id = "printSection";
    document.body.appendChild($printSection);
}
$printSection.appendChild(domClone);

<强> Fiddle