将DOM元素转换回HTML

3
我正在创建一个脚本来重新排列页面上的 <div> 元素。脚本可以将它们放入一个数组中,但该数组的内容看起来像这样:
[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement], 以下任何一种方法都没有奏效:
my_array.innerHTML
my_array.outerHTML
my_array.html
my_array.toString()
那么,我该如何将该数组还原为以下形式:
<div class="rect red"></div><div class="rect green"></div><div class="rect blue"></div><div class="rect yellow"></div>,并在页面上呈现为 div 元素?
以下是完整代码:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
 <div class="rect red"></div>
 <div class="rect green"></div>
 <div class="rect blue"></div>
 <div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
 var move = arr[ndx];
 arr.splice(ndx, 1); //from index #'ndx', remove 1 element
 arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}

$(".rect").click( function() { // rearrange the order of divs when one is clicked
 var sort = Array.from( $(this).parent().children() );
 var current_index = $(this).index();

 move_before(sort, current_index); // put each element into a new array
 var i = 0;
 var updated_arr = [];
 while (i <= sort.length) {
  updated_arr.push(sort[i]);
  i = i+1;
 }
 document.getElementById("target").innerHTML = updated_arr;
});
</script>
</body>
</html>


可能是这个:https://dev59.com/Xm855IYBdhLWcg3woVw_ - EGC
1
你需要发布你的代码。 - Barmar
@Barmar 完成了。 :-) - Mentalist
i <= sort.length 改为 i < sort.length。为什么这么多人会犯这个错误? - Barmar
好的,我已经做到了。但现在我只得到了“,,,”而不是错误信息。我之前其实对此有些犹豫,曾尝试过使用“<”而不是“<=”,但结果同样无用,只是显示出“,,,”,所以我就忽略了它。(我认为很多人会因为担心最后一个数组元素没有被计算而加上“=”,却没有停下来考虑数组从0开始这一点。)所以现在我可以看到“sort[i].outerHTML”正在工作,只是我需要摆脱结果中的逗号 - 更重要的是,弄清楚为什么第二次点击没有起作用。 - Mentalist
显示剩余2条评论
3个回答

3
使用appendChild()方法:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
 <div class="rect red"></div>
 <div class="rect green"></div>
 <div class="rect blue"></div>
 <div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
 var move = arr[ndx];
 arr.splice(ndx, 1); //from index #'ndx', remove 1 element
 arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}

$(".rect").click( function() { // rearrange the order of divs when one is clicked
 var sort = Array.from( $(this).parent().children() );
 var current_index = $(this).index();

 move_before(sort, current_index); // put each element into a new array
 var i = 0;
 var updated_arr = [];
 while (i <= sort.length) {
  updated_arr.push(sort[i]);
  i = i+1;
 }
  for(i=0;i<updated_arr.length-1;i++){
 document.getElementById("target").appendChild(updated_arr[i]);
   }
});
</script>
</body>
</html>

这类似于:

var div=document.createElement("div");
console.log(div);
document.body.appendChild(div);

3
使其正常工作的两个小改动:
  1. 在循环中使用<而不是=<,以避免额外的一次迭代。
  2. 使用Element.appendChild()将元素添加到节点中。您可以在此处阅读更多信息https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
在使用this时做得非常好!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .rect {
        width: 24px;
        height: 12px;
        border-radius: 12px;
        border: 4px solid rgba(0, 0, 0, 0.25);
        margin-bottom: 12px;
      }
      .red {
        background-color: #c21;
      }
      .green {
        background-color: #1c3;
      }
      .blue {
        background-color: #28f;
      }
      .yellow {
        background-color: #ed1;
      }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  </head>
  <body>
    <div id="target">
      <div class="rect red"></div>
      <div class="rect green"></div>
      <div class="rect blue"></div>
      <div class="rect yellow"></div>
    </div>
    <script>
      function move_before(arr, ndx) {
        //move the element one place earlier in the array
        var move = arr[ndx];
        arr.splice(ndx, 1); //from index #'ndx', remove 1 element
        arr.splice(ndx - 1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
      }

      $(".rect").click(function() {
        // rearrange the order of divs when one is clicked
        var sort = Array.from(
          $(this)
            .parent()
            .children()
        );
        var current_index = $(this).index();

        move_before(sort, current_index); // put each element into a new array
        var i = 0;
        var updated_arr = [];
        while (i <= sort.length) {
          updated_arr.push(sort[i]);
          i = i + 1;
        }
        updated_arr.map(element =>
          document.getElementById("target").appendChild(element)
        );
      });
    </script>
  </body>
</html>


0

不需要创建updated_arr。只需连接sort数组中HTMLElement对象的outerHTML

move_before(sort, current_index); document.getElementById("target").innerHTML = sort.map(elem => elem.outerHTML).join('');

还要更新您的事件绑定到 $("#target").bind('click', '.rect', function() { ...... });


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接