javascript - Why is my onclick event throwing undefined? - Stack Overflow

I have the following button:<input type="button" onclick="printDiv('print-conten

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745546677a4632369.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信