我有几个标签和段落的HTML我应该将类名分配给其中包含单引号的段落。 “
我尝试使用以下方式
$('p').each(function() {
if($("p:contains('“')").length) {
$(this).replaceWith(function () {
return "<div class='quotetext'>" + $(this).html() + "</div>";
});
}
});
但这会覆盖所有p标签。我也尝试使用最近的$(this).closest.replaceWith(function () {
但仍然没有运气。任何帮助都非常感谢。
答案 0 :(得分:4)
你需要
$('p:contains("“")').each(function () {
$(this).replaceWith(function () {
return "<div class='quotetext'>" + $(this).html() + "</div>";
});
});
演示:Fiddle
如果至少有一个if
的内容p
,而不仅仅是当前循环的内容“
,则每个循环中的replaceWith
条件将被评估为true,因此{{1}将为页面中的每个p
元素执行。
相反,您只能遍历那些p
元素作为其内容,如上所示。
答案 1 :(得分:0)
一些简单的jquery和一个jsfiddle:http://jsfiddle.net/fxomsfna/
循环遍历段落标记,测试其内容以获得一个双引号(或多或少会失败),并将has_quote
类添加到任何匹配。
$('p').each(function (i, el) {
var p = $(el);
if (/^[^"]*"[^"]*$/.test(p.text())) {
p.addClass('has_quote');
}
});