在页面加载时显示网格

时间:2018-03-23 07:09:06

标签: javascript jquery

我使用jQuery创建了一个像素艺术制作者,允许用户选择他或她喜欢的网格大小(查看其CodePen)。但是,我希望在页面加载时立即显示一个25 x 25的单元格网格,这是在使用vanilla JavaScript(CodePen)的同一项目的另一个版本中实现的。

对于我的jQuery版本,最好的方法是什么? (下面是我需要编辑的函数(makeGrid(e))的代码。)

在vanilla JS版本中,我能够通过简单地调用makeGrid(25, 25);来实现这一点,尽管它缺乏参数,这让我感到困惑。

$('.size-picker').submit(function makeGrid(e) {
  // preventDefault() method intercepts 'submit' event, which would normally submit the form and cause the page to refresh, preventing makeGrid() function from being processed
  e.preventDefault();
  // if grid is already present, clears any cells that have been filled in
  $('table tr').remove();
  // grid height value entered by user
  const heightInput = $('.input-height').val();
  // grid width value entered by user
  const widthInput = $('.input-width').val();
  // outer for loop adds desired number of rows (grid height)
  for (let i = 1; i <= heightInput; i++) {
    $('table').append('<tr></tr>');
    // inner loop adds desired number of columns as cells (td) within rows (tr) and creates a class called 'Cell' for each cell (td). Class is used later, allowing user to color cells on click
    for (let j = 1; j <= widthInput; j++) {
      // ':last' is a jQuery extension (not part of CSS specification) that selects a single element by filtering the current jQuery collection and matching the last element within it. For best performance using ':last', first select element(s) using pure CSS selector, then use .filter(":last")
      $('tr').filter(':last').append('<td></td>');
      // here, .attr() method sets attribute (class) to name provided as second argument for matched elements (td)
      $('td').attr('class', 'Cell');
    }
    $(document).add('p')
  }
  // fills in cell with chosen color when mouse button is pressed down over it. Unlike function dragColor(), doesn't require mouse to enter a cell while mouse button is being held down. Note: 'mousedown' event is fired when the mouse button is pressed but before it's released, whereas click event is fired after mousedown (click) and mouseup (release) events have completed
  $('.Cell').mousedown(function() {
  // adds chosen color to cell upon a click event. Selector 'this' refers to cell (with class 'Cell') being clicked. Variable 'color' is defined here rather than globally so JS checks whether a new color has been picked before each mousedown event
    let color = $('.color-picker').val();
    $(this).css('background-color', color);
  });
  dragColor();
});

1 个答案:

答案 0 :(得分:1)

更改makeGrid函数,使其单独声明。

在该函数内部,确保在调用e之前定义preventDefault()

然后添加:

$(window).on('load', makeGrid);

更新了Codepen:https://codepen.io/anon/pen/JLJvGM