我有这个简单的标记:
<p> some content here </p>
我想将其分解为
<p> some </p> content <p> here </p>
使用javascript(或使用jQuery帮助)。
我想打破html p
标记,以便我的特定字词(例如content
)不在p
之内。我想找到跨浏览器和有效的解决方案
提前谢谢。
答案 0 :(得分:2)
(function () {
$.fn.extend({
splitAt: function (splitter) {
this.each(function () {
var $replacement = $(), $org = $(this);
$.each($org.text().split(splitter), function (_, val) {
$replacement = $replacement.add($org.clone().html(val)).add(document.createTextNode(splitter));
});
$org.replaceWith($replacement.slice(0, -1));
});
return $(this.selector, this.context);
}
});
}(jQuery));
$('p').splitAt('content').css('background', 'lightblue');
答案 1 :(得分:1)
试试这个..只需更改选择器和要从选择器中挑选和排除的单词
$('p').text($('p').text().replace('content','</p>content<p>'));
答案 2 :(得分:0)
查看Text.splitText
和示例。
答案 3 :(得分:0)
试试这个:
$('p').each(function() {
$(this).html($(this).html().replace('content','</p>content<p>'));
})
使用每个循环选定的文本设置p
元素的HTML,方法是获取其HTML并将content
替换为</p>content<p>
<强>更新强>
感谢@Yoshi在下面的评论...没有each()循环的更好方法:
$('p').html(function (_, html) {
return html.replace('content','</p>content<p>');
});
答案 4 :(得分:0)
我为你做了这个:
现场演示: http://jsfiddle.net/oscarj24/A4efg/1/
这适用于<p></p>
标记内的任何文字。
HTML:
<p> some content here </p>
<input type="button" id="btn" value="Do it!"/>
<br/><br/>
results will be here:
<div id="result"></div>
JS:
$('#btn').click(function(){
// clean the "result" div each time you invoke "click"
$('#result').html('');
// get the text inside "<p></p>" tags
var str = $('p').html();
// make an array for all elements inside tag
// result: ["", "some", "content", "here", ""]
var substr = str.split(' ');
// remove "space" elements from the array
// result: ["some", "content", "here"]
removeFromArray(substr, '');
// populate the "result" div where i = index, e = element
// result:
// some
// content
// here
$.each(substr, function(i, e){
$('#result').append('<p> ' + substr[i] + ' </p>');
});
});
/* Function to remove element from js array */
function removeFromArray(arr){
var what, a= arguments, L= a.length, ax;
while(L> 1 && arr.length){
what= a[--L];
while((ax= arr.indexOf(what))!= -1){
arr.splice(ax, 1);
}
}
return arr;
}
CSS - 只是为了风格: - )
div#result{
color: red;
}
希望这会有所帮助:-)