如何在javascript中创建指向pdf的链接?

时间:2013-10-01 09:34:11

标签: javascript pdf hyperlink

我是一名使用XHTML模板创建电子商务网站的新手。我想在某些项目下添加免责声明,但不是全部。为避免在每个项目下键入免责声明(如果免责声明发生变化,将来避免出现问题),我想使用javascript创建一个副本块,当我指向它时,会添加免责声明。我已经成功完成了(是啊!),但是,在免责声明中是一个pdf的链接。当我使用html链接到pdf时,它失败了。我知道这可能是因为我没有正确的语法,因为html是javascript代码的“内部”。有人可以帮忙吗?

这就是我所拥有的:

//<![CDATA[
function openPDF(file)
{
window.open (file, 'resizable,scrollbars');
}
//]]>
</script>

<script type="text/javascript">
//<![CDATA[
onload=function()
{
var txt=document.getElementById("myDiv")
txt.innerHTML="Photos do not represent actual size. Refer to measurements for sizing.
Measurements are approximate. Colors shown may differ depending on your computer
settings. Colors described are subjective and colors may vary from piece to piece,
depending on the natural properties of the stones. To learn more, see our <a href="#" 
onClick="openPDF('www.shop.site.com/media/JewelryGuide.pdf')">Jewelry Guide</a>.";
}
//]]>
</script>

以下是我用来调用它的代码:

<div id="myDiv"></div>`

2 个答案:

答案 0 :(得分:1)

如下所示的功能我会相信...     

function openPdf(e, path) {
    // stop the browser from going to the href
    e = e || window.event; // for IE
    e.preventDefault(); 

    // launch a new window with your PDF
    window.open(path, 'somename', ... /* options */);

}

嗨,我做了一个小小的小提琴希望它有帮助...... http://jsbin.com/aQUFota/1/edit

答案 1 :(得分:0)

1)你在该文本字符串中有换行符。 2)你需要逃脱几个引号。我选择交换引号并转义文件名周围的引号。

txt.innerHTML = 'Photos do not represent actual size. Refer to measurements for sizing. Measurements are approximate. Colors shown may differ depending on your computer settings. Colors described are subjective and colors may vary from piece to piece, depending on the natural properties of the stones. To learn more, see our <a href="#" onClick="openPDF(\'www.shop.site.com/media/JewelryGuide.pdf\')">Jewelry Guide</a>.';

如果你不想要一条长线,你可以像这样划掉线条:

txt.innerHTML = 'Photos do not represent actual size.' +
'Refer to measurements for sizing. Measurements are approximate.' +
'Colors shown may differ depending on your computer settings.' +

甚至:

txt.innerHTML = [
  'Photos do not represent actual size.',
  'Refer to measurements for sizing. Measurements are approximate.',
  'Colors shown may differ depending on your computer settings.'
].join('');