【问题标题】:Print only html table using javascript使用 javascript 仅打印 html 表
【发布时间】:2015-04-13 16:54:27
【问题描述】:

我有以下带有 Java 功能的基本 html 表格,仅打印表格内容但是单击打印按钮时什么也不做,我认为可能是 java 编码的问题,但是它不起作用我可以得到第三对吗请提供帮助的眼睛

<html>
<body>

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

<br />
<br />

<button>Print me</button>

<script>
function printData()
{
   var divToPrint=document.getElementById("printTable");
   newWin= window.open("");
   newWin.document.write(divToPrint.outerHTML);
   newWin.print();
   newWin.close();
}

$('button').on('click',function(){
printData();
})
</script>
</body>
</html>

【问题讨论】:

  • 您遇到了什么问题?
  • @Paco 运行代码时,打印按钮什么也不做
  • 你看懂你贴的代码了吗?如果是这样,您应该编辑您的帖子,准确解释它应该做什么。你期望会发生什么?等等
  • @Paco 是的表有一个 ID="printTable" 引用 java 函数“PrintData”,当单击按钮时,它应该只打印具有 PrintTable Id 的表,但是没有发生单击按钮时,这就是我正在寻求帮助的原因
  • 删除 outerHtml 并尝试document.getElementById("printable").innerHTML

标签: java html printing


【解决方案1】:

使用 javascript 时,查看浏览器的控制台通常很有用。打开这个页面后,我的有错误:

ReferenceError: $ is not defined

$ 是 jQuery 插入的全局变量。尝试添加

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

到代码。这将包括 jQuery 库。

【讨论】:

  • 请务必在使用 $ 之前添加它 - 在 &lt;button&gt;Print me&lt;/button&gt; 之后将是一个好地方。
【解决方案2】:

对 javascript 函数的调用不正确。当您使用“$”符号时,这意味着您正在使用 JQuery。你有两个选择:

1 - 将 jquery 库包含到您的页面中:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>

2 - 在“onclick”事件的按钮上直接调用 javascript 函数。这是您的最佳选择:

<button onclick="printData()">Print me</button>

【讨论】:

    【解决方案3】:
    Change this var divToPrint=document.getElementById("printTable");
    to this var divToPrint=document.getElementById("<%=printTable.ClientID>");
    
    and add jquery library <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 2019-01-03
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多