使用jquery在特定标记之前和之后向文本添加包装标记
我正在尝试在包含段落和中断标记的重复html块上创建详细信息和摘要标记结构。
我的div有一个特定的类,我想用jquery来查找内容。 具体来说,分配给我的css类的每个段落的第一个break标记将用作标记,第一个中断之前的所有内容都由
标记包装,整个匹配段落中的所有内容都包含在内部。标签对。
所以给出一个前后html的例子。 在改变之前,它看起来像这样……
this should be in a summary
this would be within the expandable details tag
它最终应该像……
this should be in a summary
this would be within the expandable details tag
我以为我使用以下代码…
$(".matchingClass").each(function() { $(this).prepend(""); $(this).find("br").first().before().prepend("
"); $(this).append(""); });
但我现在意识到jquery / javascript总是自动插入结束标签。 因此,只要我应用的3个命令中的第一个运行,html就不会结束我的预期。
有人可以帮忙吗?
演示: http : //jsfiddle.net/RJktH/
$('.matchingClass').each(function () { var t = $(this).html(); $(this).html('' + t.replace('
', ' ')); }); $('.matchingClass').wrapInner('');
你可以用这个:
$('.matchingClass').each(function(){ $(this).contents().first().wrap(''); $(this).contents().wrapAll(''); });
小提琴: http : //jsfiddle.net/kkDFe/
最简单的解决方案可能是简单的字符串解析:
$('.matchingClass').each(function() { var html = $(this).html(); var parts = html.split('
'); var firstPart = parts.splice(0,1); // support multiple
elements html = '' + firstPart + '
' + parts.join('
') + ''; $(this).html(html); });
当然, 理想的解决方案是更改服务器端代码以生成所需的标记,而无需使用javascript来处理它。
无论如何都不漂亮,但它有效:
var $p = $('.matchingClass') var $details = $('') $p.contents().filter(function() { return this.nodeType == 3; // textNode }).each(function(i, node) { i == 0 ? $(' ', { text: node.nodeValue }).appendTo($details) : $details.append(node.nodeValue) }); $p.empty().append($details);
示例小提琴
- 在jQuery mousedown处理程序中添加叠加层后,Internet Explorer泄漏了单击事件
- 什么时候使用基于DOM的Generation而不是使用strings / innerHTML / JQuery来生成DOM内容?
- 如何将DOM附加到Angular 2组件并仍然获取封装样式
- 无法通过jquery获取ajax加载图像的高度和宽度
- 如何使用html标记从window.getSelection()。getRangeAt(0)中包装文本选择?
- jQuery与普通javascript:构建DOM树时append和appendChild之间的差异
- 如何在不计算扩展实体的情况下找到标签(元素)的字符串索引?
- 如何使用Javascript(jQuery)确定’line-height’?
- jQuery克隆节点错误