Jquery包含类似的内容

时间:2017-02-16 23:08:12

标签: javascript jquery

我有一个问题我想用jQuery解决,但我不确定如何去解决它。我有一个重复属性div的{​​{1}}列表。

data-content

现在:https://jsfiddle.net/L5a0netr/

我试图在父元素中包含共享相同<div class="element" data-content="string one"> <p>one</p> </div> <div class="element" data-content="string one"> <p>one</p> </div> <div class="element" data-content="string one"> <p>one</p> </div> <div class="element" data-content="string two"> <p>two</p> </div> <div class="element" data-content="string two"> <p>two</p> </div> <div class="element" data-content="string three"> <p>three</p> </div> <div class="element" data-content="string three"> <p>three</p> </div> <div class="element" data-content="string three"> <p>three</p> </div> <div class="element" data-content="string three"> <p>three</p> </div> 属性的div,如下所示:

data-content

以下是改变后的样子:https://jsfiddle.net/mxcjmdf8/

1 个答案:

答案 0 :(得分:0)

你必须创建一个新元素来包装并将每个元素放入其中,这将完全符合您的要求:

var div = document.createElement('div');
div.innerHTML = "<h2>string one</h2>";
$('[data-content="string one"]').each(function(){
        div.appendChild(this);
})
div.className = "wrap";
document.body.appendChild(div);

然后你为每个你想创造的包裹做这件事。

这是生成的html:

enter image description here

最后,这是有效的:

// STRING ONE
var div = document.createElement('div');
div.innerHTML = "<h2>string one</h2>";
$('[data-content="string one"]').each(function(){
		div.appendChild(this);
})
div.className = "wrap";
document.body.appendChild(div);

// STRING TWO
var div = document.createElement('div');
div.innerHTML = "<h2>string two</h2>";
$('[data-content="string two"]').each(function(){
		div.appendChild(this);
})
div.className = "wrap";
document.body.appendChild(div);

// STRING THREE
var div = document.createElement('div');
div.innerHTML = "<h2>string three</h2>";
$('[data-content="string three"]').each(function(){
		div.appendChild(this);
})
div.className = "wrap";
document.body.appendChild(div);
.element {
  border-bottom: 1px solid #000;
  margin-bottom: 20px;
   padding-bottom: 20px;
}
.wrap {
  border: solid 2px blue;
  margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element" data-content="string one">
    <p>one</p>
</div>

<div class="element" data-content="string one">
    <p>one</p>
</div>

<div class="element" data-content="string one">
    <p>one</p>
</div>

<div class="element" data-content="string two">
    <p>two</p>
</div>

<div class="element" data-content="string two">
    <p>two</p>
</div>

<div class="element" data-content="string three">
    <p>three</p>
</div>

<div class="element" data-content="string three">
    <p>three</p>
</div>

<div class="element" data-content="string three">
    <p>three</p>
</div>

<div class="element" data-content="string three">
    <p>three</p>
</div>

] 1