简体   繁体   English

我想使用jQuery的包含选择器

[英]I want to use Contains selector of jquery

I have a variable [ITEM_NAME] that stores an item name from a shopping cart. 我有一个变量[ITEM_NAME] ,用于存储购物车中的商品名称。 I want to check whether the value in [ITEM_NAME] is like one of the following strings: 我想检查[ITEM_NAME]的值是否类似于以下字符串之一:

"CHICAGO NEW"
"CHICAGO OLD"
"CHICAGO TEXT"
"CHICAGO PURE"

In pseudocode: 用伪代码:

if ([ITEM_NAME].contains("CHICAGO"))

I want a condition that will be satisfied for all strings that start with "CHICAGO". 我希望所有以“ CHICAGO”开头的字符串都可以满足的条件。

This has nothing to do with jQuery selectors. 这与jQuery选择器无关。 Simply use the indexOf method to find whether the string stored in your variable contains the substring "CHICAGO": 只需使用indexOf方法来查找存储在变量中的字符串是否包含子字符串“ CHICAGO”:

if (yourString.indexOf("CHICAGO") !== -1) {
    //do something
}

If you want to check whether the string starts with the text "CHICAGO", you can use: 如果要检查字符串是否以文本“ CHICAGO” 开头 ,则可以使用:

if (yourString.indexOf("CHICAGO") == 0) {
    //do something
}

You can read more about indexOf here . 您可以在此处阅读有关indexOf更多信息。

EDIT: In your comments to Derek's answer, you mentioned that matching should be case insensitive (although this information isn't present in the question). 编辑:在您对Derek答案的评论中,您提到匹配应该不区分大小写(尽管问题中不存在此信息)。 If that is the case, simply use: 如果是这种情况,只需使用:

if (yourString.toUpperCase().indexOf("CHICAGO") == 0) {
    //do something
}

.contains() checks to see if an element is a direct descendent of another DOM element. .contains()检查一个元素是否是另一个DOM元素的直接后代。 It is not useful at all for what you are trying to do. 对于您要尝试执行的操作根本没有用。

You should use .indexOf() . 您应该使用.indexOf()

If you need your test to be case-sensitive: 如果您需要对测试区分大小写:

if ([ITEM_NAME].indexOf('Chicago') === 0)

Otherwise, if it needs to be case-insensitive: 否则,如果需要区分大小写:

if ([ITEM_NAME].toUpperCase().indexOf('CHICAGO') === 0)

if (string.match(/chicago/i)) {...}不区分大小写,我会使用一个正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM