0

我对我的 HTML 设计有疑问。我有<div> ... </div>一个固定位置的部分。我希望在标签<div></div>内的任何地方重用它。body

我用 jQuery 和 JavaScript 用 , , 的方法尝试innerhtml('...')after('...')append('...')。它有效,但我不想用引号解释这 100 行,还有一件事。我希望不止一次地包括这<div></div>一点。

示例代码格式。

<html>
<head>
....
</head>

<body>
...
   <div id='includes_div'>       <!-- It hides on form load -->
      ...
      ...     <!-- having 100 of lines -->
   </div>

   <div id='div1'>
       <!-- want to include here -->
      ...
   </div>


   <div id='div2'>
       <!-- want to include here -->
      ...
   </div>
</body>
</html>

jQuery或JavaScript可以吗?

4

2 回答 2

5

这应该工作:

var cont = $('#includes_div').html();
$('#div1').append(cont);
$('#div2').append(cont);
于 2013-03-30T13:26:03.927 回答
2

有很多方法可以做到这一点,以下只是我看到常用的两种。

第一个是使用 jQuery 'clone()' 方法:

var toClone = $('#includes_div');
var cloneContainers = $('#div1, #div2');

cloneContainers.each(function() {
    var clonedDiv = toClone.clone();
    clonedDiv.attr('id', '');
    this.append(clonedDiv);   
});

This will give you an exact clone of the original div and put it in each container. As it is an exact clone you need to prevent id conflicts.

Another way is to just use the content of the first div, rather than the whole of it.

var content = $('#includes_div').html();
var containers = $('#div1, #div2');

containers.each(function() {
    this.append(content);   
});

Obviously the code above is written to help break down the process, it's possible to write them both in a more compact form.

于 2013-03-30T13:35:10.613 回答