Javascript jQuery contains() 具有可变语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2191419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:11:03  来源:igfitidea点击:

jQuery contains() with a variable syntax

javascriptjquerysyntax

提问by Mircea

I have an "uncaught exception: Syntax error, unrecognized expression: )" in a jQuery application.

我在 jQuery 应用程序中有一个“未捕获的异常:语法错误,无法识别的表达式:)”。

The code is:

代码是:

<script>
    $(document).ready(function(){                      
        $('.drag').click(function() {
           $('.drag').each(function(i) {
                $(this).addClass('test' + i)
            });  

           var vtxt = $(this).text();
           $("p").removeClass("on");
           $("p:contains("+ vtxt +")").addClass("on");

       });
    });

The problem is when I add the variable vtxt to a contains: $("p:contains("+ vtxt +")").addClass("on");

问题是当我将变量 vtxt 添加到 contains: $("p:contains("+ vtxt +")").addClass("on");

I've tried several quotes but it just does not work. What is the right syntax for adding a variable to a contains?

我已经尝试了几个引号,但它不起作用。将变量添加到包含的正确语法是什么?

回答by Andrew Hare

Try this:

尝试这个:

$("p:contains('" + vtxt + "')").addClass("on");

回答by Nelo Mitranim

Old question, but I must leave a note for future generations. Andrew's answer (the accepted one) didn't work for me. What didwork was using a pre-made string as selector. Borrowing OP's examples:

老问题,但我必须为后代留下一张纸条。安德鲁的回答(接受的回答)对我不起作用。什么的工作使用预制的字符串作为选择了。借用OP的例子:

var selector = "p:contains("+ vtxt +")";
$(selector).addClass("on");

回答by combuilder

I have used this answer in order to solve a similar problem.
I want to prevent the use of "and '

我已经使用这个答案来解决类似的问题。
我想阻止使用"'

When using $("p:contains('" + valor + "')").addClass("on");, it works.

使用时$("p:contains('" + valor + "')").addClass("on");,它的工作原理

But when using $('p:contains('" + valor + "')**'**).addClass("on"), it does not!

但是使用的$('p:contains('" + valor + "')**'**).addClass("on")时候就不行了