2015-10-13 51 views
2

我有以下表中的TD文本(8" & 12 “)的jQuery包含选择不倒逗号和breackt工作

我的代码是

var match = $('#table_body > tr > td:contains("' + searchterm + '")'); 

,当我试图找到(8” & 12 “)这得到以下错误

错误:语法错误,不能识别的表达式::含有(” “)”

最后“)双字符s正在创建问题它是什么解决方案我尝试了转义字符串(添加斜线)错误消失了,但没有搜索结果与此

+0

你可以张贴HTML? –

+0

​​ \t \t

10050 - Concrete - Place CMU Blocks above concrete footing (8" & 12")
\t \t –

+0

https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-已经使用了-css-notation/ – epascarello

回答

0

它适用于单引号围绕您的td:contains('some text with "quotes"')。该文档不会使用双引号列出作为有效的选择。请注意,你并不需要周围的引号,你可以使用单词。无论您的文本是包含单引号还是双引号,它都可以工作。

var match = $("#table_body > tr > td:contains('" +searchterm+ "')"); 
// or without quotes altogether 
var match = $("#table_body > tr > td:contains(" +searchterm+ ")"); 

例子:

var text = '8" 12"'; 
 
var text2 = '5" 6"' 
 
var text3 = '2\' 4"'; 
 
var text4 = "Testing (1' 3')"; 
 

 

 
// Quotes are allowed 
 
$("div:contains('"+text+"')").css('background-color', 'red'); 
 

 
// But not necessary 
 
$("div:contains("+text2+")").css('background-color', 'yellow'); 
 

 
// Works with mixed single and double quotes 
 
$("div:contains("+text3+")").css('background-color', 'gray'); 
 

 
// However, it doesn't support parentheses, you'll have to search it yourself 
 
// And make sure you escape regex special characters 
 

 
// Escapes any special characters 
 
RegExp.escape = function(s, flags) { 
 
    return new RegExp(s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); 
 
}; 
 

 
console.log(RegExp.escape("1' 3')")) 
 
$('div').filter(function(i, el) { 
 
    return $(el).text().match(RegExp.escape("1' 3')")); 
 
}).css('background-color', '#fef0e4');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div>8" 12"</div> 
 
<div>5" 6"</div> 
 
<div>2' 4"</div> 
 
<div>1' 3')</div>

+0

我试过但不工作 var searchterm ='“)'; $('#table_body> tr> td:contains(”'+ searchterm.replace(/ “/ g,”\\\“”)+'“)'); –

+0

@NavneetGarg最初的尝试没有奏效,但我添加了一个工作示例的答案 –

+0

是的这是工作谢谢,但我想知道如果用户键入')这比这个代码生成错误 –