2

假设我有 2 个 div:

<div>&pound; 21.99</div>
<div>&pound;</div>

如果我只想选择仅包含 £ 符号的 div,我将如何处理?

我努力了:

if ($('div:contains("&pound;")').length > 0) 
{
   $(this).addClass("pound");
}
4

4 回答 4

4

我相信问题是浏览器正在转换 HTML 转义字符,所以你需要寻找实际的字符......我测试了这个并且它有效

$(document).ready(function(){
 $('div').each(function(){
  if ($(this).html() == "£"){
   $(this).addClass("pound");
  }
 })
})
于 2009-10-08T02:38:34.830 回答
1
$('div:contains("&pound;")').each( function() {
     var text = $(this).html();
     if (text && text.match(/\s*&pound;\s*/)) {
        $(this).addClass('pound');
     }
});
于 2009-10-08T00:21:03.247 回答
0

tvanfosson 的代码允许在 £ 符号的任一侧使用空格,但正则表达式可以做一些修改:

$('div:contains("&pound;")').each( function() {
    var text = $(this).html();
    if (text && text.match(/^\s*&pound;\s*$/)) {
        $(this).addClass('pound');
        }
    });

注意表示字符串开头和结尾的“^”和“$”。

于 2009-10-08T11:16:06.050 回答
0

试试.filter。

我在 SO 上发现了另一个带有相关信息的问题:

jQuery中的正则表达式字段验证

于 2009-10-08T00:17:23.767 回答