2

<br/>
<a href="#">News</a>
<br/>
This is the first line
<br/>
This is the second line
<br/>
This is the third line

各テキスト行をタグで囲む方法はありますか?テキストの内容は固定されておらず、動的に表示されます。jquery:containsセレクターを使用する場合、動的にコンテンツ行を作成する方法はありません。ありがとう

4

3 に答える 3

1

HTMLをコンテナに配置し、次のjQueryを適用する必要があります。div id="data"を使用しました。
これは動作するコードです:

<div id="data">
    <br/>
    <a href="#">News</a>
    <br/>
    This is the first line
    <br/>
    This is the second line
    <br/>
    This is the third line
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    var data = $('#data').html();
    var sbstr = data.split('<br>');

    var new_data = '';
    // wrap each line with a tag, you can use 'a', 'li' or any other tag.
    for(x in sbstr){
        new_data += '<a href="#">'+sbstr[x]+'</a><br>';
    }

    //replace old data with new one
    $('#data').html(new_data);
});
</script>
于 2012-05-02T05:45:35.973 に答える
0

id=testのラッパーがあると仮定します。

var test = $('#test');
var temp = test.html().split('<br>');
var insert = "";

$.each(temp, function(index) {
   insert += '<div class="wrap">' + this + '</div>';       
});
test.html(insert);

ここでの例:http://jsfiddle.net/GMJxG/1/

編集:@ Arvind07は私をそれに打ち負かしました!例として、これをここに残しておきます。

于 2012-05-02T05:57:32.000 に答える
0
<div id="contents">
    <br/>
    <a href="#">News</a>
    <br/>
    This is the first line
    <br/>
    This is the second line
    <br/>
    This is the third line
</div>

$('#contents').contents().remove('br').filter(function() {
    var node = $(this);
    if(node.context.nodeType == 3 && node.context.length != 1) {
      node = node.wrap('<div/>');
    }
    return node;
});
于 2012-05-02T08:39:44.093 に答える