<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 选择器,动态内容行就没有办法了。谢谢
<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 选择器,动态内容行就没有办法了。谢谢
您需要将 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>
<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;
});
假设你有一个 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 打败了我!我将把它留在这里作为示例。