【问题标题】:Converting DOM elements back into HTML将 DOM 元素转换回 HTML
【发布时间】:2020-02-26 09:08:45
【问题描述】:

我正在创建一个脚本来重新排列页面上的<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>

【问题讨论】:

  • 你必须在数组元素上调用outerHTML,而不是数组。
  • @Barmar 谢谢。当我尝试my_array[i].html 或类似的东西(如外部和内部)时,我得到TypeError: my_array[i] is undefined 我做错了什么?
  • 你需要发布你的代码。
  • @Barmar 完成。 :-)

标签: javascript html arrays dom


【解决方案1】:

两个小改动使它可以工作:

  1. 在循环中使用&lt; 而不是=&lt; 以避免一次额外的迭代。
  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>

【讨论】:

    【解决方案2】:

    使用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】:

      无需创建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() { ...... });

      【讨论】:

        猜你喜欢
        • 2022-01-13
        • 2021-04-27
        • 2019-02-24
        • 2011-03-07
        • 1970-01-01
        • 2010-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多