doc.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. !(function () {
  2. window.console = window.console || {
  3. log: $.noop
  4. };
  5. var codes = {};
  6. var debug = location.href.indexOf('Users/tangbin') !== -1;
  7. $(function () {
  8. console.log('你可以在调试器中粘贴本页示例代码运行');
  9. var RE = /[\n\s\t]*?\/\/\.\.[\r\n]/;
  10. $('pre code').each(function (index) {
  11. var $this = $(this);
  12. var code = $this.text();
  13. // 忽略不完整的代码片段
  14. // 开头使用"//.."表示
  15. if (RE.test(code)) {
  16. $this.text(code.replace(RE, ''));
  17. return;
  18. }
  19. try {
  20. codes[index] = new Function(code);
  21. } catch (e) {
  22. return;
  23. }
  24. $this
  25. .after('<div class="doc-line"></div>'
  26. +'<button data-code="' + index + '">运行</button>');
  27. });
  28. // 回到顶部
  29. var $top = $('<a class="doc-gotop" href="javascript:;">TOP</a>')
  30. .on('click', function () {
  31. $(window).scrollTop(0);
  32. return false;
  33. });
  34. $('body').append($top);
  35. });
  36. var runCode = function (id) {
  37. codes[id]();
  38. var api = dialog.getCurrent();
  39. if (debug && api) {
  40. console.log(api);
  41. }
  42. };
  43. $(document).on('click', 'button[data-code]', function () {
  44. var id = $(this).data('code');
  45. runCode(id);
  46. return false;
  47. }).on('click', 'h1 [id], h2 [id], h3 [id], h4 [id], h5 [id], h6 [id]', function () {
  48. var id = this.id;
  49. location.hash = id;
  50. });
  51. }());