admin管理员组

文章数量:1431398

I have the following button:

<input type="button" onclick="printDiv('print-content')" value="print a div!"/>

And the following JavaScript right below:

<script>
$(function() {
  function printDiv(divName) {
   alert('s')
     var printContents = document.getElementById(divName).innerHTML
     w=window.open()
     w.document.write(printContents)
     w.print()
     w.close()
  }
})
</script>

When I click printDiv, though I get the following error:

Uncaught ReferenceError: printDiv is not defined payment-history:398 onclick

I really don't get it.

I have the following button:

<input type="button" onclick="printDiv('print-content')" value="print a div!"/>

And the following JavaScript right below:

<script>
$(function() {
  function printDiv(divName) {
   alert('s')
     var printContents = document.getElementById(divName).innerHTML
     w=window.open()
     w.document.write(printContents)
     w.print()
     w.close()
  }
})
</script>

When I click printDiv, though I get the following error:

Uncaught ReferenceError: printDiv is not defined payment-history:398 onclick

I really don't get it.

Share Improve this question asked Apr 14, 2015 at 3:38 wycwyc 55.4k83 gold badges256 silver badges441 bronze badges 1
  • 1 I remend to read quirksmode/js/introevents.html if you want to learn more about event handlers. – Felix Kling Commented Apr 14, 2015 at 4:06
Add a ment  | 

1 Answer 1

Reset to default 6

Because printDiv is not in global scope. You have wrapped it with a function. So, printDiv scope is within that immediate function and not global.

JavaScript scoping and Hoisting

本文标签: javascriptWhy is my onclick event throwing undefinedStack Overflow