jQuery:包含html [英] jQuery :contains with html
问题描述
我有一个包含逗号分隔的数字列表的表格,如下所示:< td> 72,76,81< / td>
。我正在尝试选择不包含特定数字的表格单元格。这个选择器有效:
$(td:not(:contains('76')),$ table)
问题是可能有行包含'576'或'761'等。
<为了解决这个问题,我决定在每个号码周围放一个
< span>
,现在它就是:< td><跨度> 72℃; /跨度>,<跨度> 76< /跨度>,<跨度> 81< /跨度>< / TD>
。我的选择器现在是: $(td:not(:contains('< span> 76< / span>')) ,$ table)
当我在Firebug中调试这个选择器时,它正在返回一些实际上不存在于HTML源代码中的span标记,而不是正确的< td>
s。
基本上,放''code> < span> '在中:contains()
字符串正在破坏选择器。是否有任何选择器类似于:contains()
,当HTML传递给它时它会正常工作?或者我可以通过某种方式选择< span>
中的整个字符串?
BTW,这个网站正在使用jquery 1.3.2。
如果你想坚持< span>
s,即使使用jQuery 1.3.2也可以:
var $ tds = $(table td)。filter(function(){
return!$(this).find('span')。filter(function(){
return $(this).text()=== '76';
})。长度;
});
http://jsfiddle.net/mattball/PFk8H/
另一方面,如果你想回到原来的标记,这实际上很容易:
var $ tds = $(table td) .filter(function(){
return!$(this).text()。match(/ \ b76 \b /);
});
http://jsfiddle.net/mattball/L6AFz/
使用变量正则表达式,使用 new RegExp(string)
构造函数语法:
var n = 76,
re = new RegExp( \\b+ n +\\b);
var $ tds = $(table td)。filter(function(){
return!$(this).text()。match(re);
});
http://jsfiddle.net/mattball/hKQH7/
I have a table that contains comma separated lists of numbers like this: <td>72,76,81</td>
. I'm trying to select the table cells that don't contain a particular number. This selector worked:
$("td:not(:contains('76'))", $table)
The issue is that there may be rows that contain '576' or '761', etc.
To solve that issue, I decided to put a <span>
around each number, so that it's now: <td><span>72</span>,<span>76</span>,<span>81</span></td>
. My selector is now:
$("td:not(:contains('<span>76</span>'))", $table)
When I debug this selector in Firebug, it's is returning some span tag that doesn't actually exist in the HTML source, instead of the correct <td>
s.
Basically, putting the '<span>
' in the :contains()
string is breaking the selector. Is there any selector similar to :contains()
that will work properly when HTML is passed to it? Or is there some way I can select by the entire string inside the <span>
?
BTW, this site is using jquery 1.3.2.
If you want to stick with <span>
s, this works, even with jQuery 1.3.2:
var $tds = $("table td").filter(function() {
return !$(this).find('span').filter(function () {
return $(this).text() === '76';
}).length;
});
http://jsfiddle.net/mattball/PFk8H/
On the other hand, it's actually really easy if you want to go back to the old markup:
var $tds = $("table td").filter(function() {
return !$(this).text().match(/\b76\b/);
});
http://jsfiddle.net/mattball/L6AFz/
To use a variable in the regex, use the new RegExp(string)
constructor syntax:
var n = 76,
re = new RegExp("\\b" + n + "\\b");
var $tds = $("table td").filter(function() {
return !$(this).text().match(re);
});
http://jsfiddle.net/mattball/hKQH7/
这篇关于jQuery:包含html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!