【问题标题】:Can anyone help me make my JavaScript faster?谁能帮我让我的 JavaScript 更快?
【发布时间】:2023-04-06 23:36:01
【问题描述】:

在我的程序中,我正在使用 JavaScript 制作 div 框,制作 50X50 网格似乎需要相当多的时间。制作 20x20 网格甚至需要一些时间。我已经查找了如何使我的代码更快,但没有任何建议产生微不足道的差异。

这是一个奥丁项目

https://jsfiddle.net/Mulk/yc5rsf1m/#&togetherjs=dVAh1FK7On

$(document).ready(function(){
// Defalut Grid is 16x 16 Grid
CreateBox(16);
CallMeMaybe();

$("#gridbtn").click(function(){
  $(".odd").remove();
  var numbox =parseInt(prompt("How many boxes would like?"));
  CreateBox(numbox); 

  });

  function CreateBox(a) {
  var  wh = (500/a), i , j ;
  for(i=0;i<a;i++){
  for(j=0;j<a;j++){
  $div = $('<div/>').appendTo('#container').addClass(".odd").attr('class','odd').width(wh).height(wh);

  CallMeMaybe();





  }}

};

// Play with me


function CallMeMaybe(a){
$(".odd").hover(function(){


    var r = Math.floor(Math.random() * (256 - 0) + 0);
    var g = Math.floor(Math.random() * (256 - 0) + 0);
    var b = Math.floor(Math.random() * (256 - 0) + 0);
    var color = "rgb("+r+","+g+","+b+")"
    $(this).css("background-color", color);


});
};





// Play with me






});

【问题讨论】:

标签: javascript jquery html performance


【解决方案1】:

不要将每个新元素都附加到 DOM,这非常昂贵,而是先将所有元素附加到文档片段,然后将整个内容附加到 DOM。

【讨论】:

  • var df = $('&lt;div/&gt;'); for(...) { $(df).append('&lt;div/&gt;'); } $('#container').append(df);
【解决方案2】:

这应该更快。它创建了一个 div 数组并将它们一次性附加到 DOM 中。 div 是使用属性创建的,而不是在将它们添加到 DOM 后更改它们的属性。它还在创建时附加悬停处理程序,而不是在创建所有框后附加它。这应该会显着减少需要进行的 DOM 操作次数。

$(function(){

  function createBox(boxesInRow) {
    var wh = (500/boxesInRow), i , j, divs = [];
    for(i = 0; i < boxesInRow; i++){
        for(j = 0; j < boxesInRow; j++){
            divs.push($('<div/>', {
                "class":'odd',
                height: wh + 'px',
                width: wh + 'px',
                hover: hoverCallback
            }));
        }
    }

    $('#container').empty().append(divs);
  }

  function hoverCallback() {
    var r = Math.floor(Math.random() * 256),
        g = Math.floor(Math.random() * 256),
        b = Math.floor(Math.random() * 256);
    $(this).css("background-color", "rgb("+r+","+g+","+b+")");
  }

  // Default Grid is 16x16 Grid
  createBox(16);

  $("#gridbtn").click(function() {
    var numbox = parseInt(prompt("How many boxes would you like per row?"));
    createBox(numbox); 
  });

});

【讨论】:

  • 谢谢你,当我更多地操作这个时我会记住这一点:)
  • 速度快多了。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 2022-08-10
  • 2011-05-03
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多