假设我有 2 个 div:
<div>£ 21.99</div>
<div>£</div>
如果我只想选择仅包含 £ 符号的 div,我将如何处理?
我努力了:
if ($('div:contains("£")').length > 0)
{
$(this).addClass("pound");
}
假设我有 2 个 div:
<div>£ 21.99</div>
<div>£</div>
如果我只想选择仅包含 £ 符号的 div,我将如何处理?
我努力了:
if ($('div:contains("£")').length > 0)
{
$(this).addClass("pound");
}
我相信问题是浏览器正在转换 HTML 转义字符,所以你需要寻找实际的字符......我测试了这个并且它有效
$(document).ready(function(){
$('div').each(function(){
if ($(this).html() == "£"){
$(this).addClass("pound");
}
})
})
$('div:contains("£")').each( function() {
var text = $(this).html();
if (text && text.match(/\s*£\s*/)) {
$(this).addClass('pound');
}
});
tvanfosson 的代码允许在 £ 符号的任一侧使用空格,但正则表达式可以做一些修改:
$('div:contains("£")').each( function() {
var text = $(this).html();
if (text && text.match(/^\s*£\s*$/)) {
$(this).addClass('pound');
}
});
注意表示字符串开头和结尾的“^”和“$”。