简体   繁体   English

检查元素是否包含JavaScript或jQuery中的三个字符串之一

[英]Check if element contains one of three string in JavaScript or jQuery

When DOM ready, I would like to check if an element on the page contains one of three strings. 当DOM准备就绪时,我想检查页面上的元素是否包含三个字符串之一。 Currently, I am doing it like this, but this is not working as expected because indexOf is usually used in combination with arrays: 目前,我正在这样做,但是由于indexOf通常与数组结合使用,因此无法正常工作:

jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML.indexOf('iDEAL' || 'Sofortbanking' || 'Bancontact / MisterCash') > 1

How can I rewrite this in the most effective way to check if the element contains one of the three strings? 如何以最有效的方式重写此代码,以检查元素是否包含三个字符串之一?

var html = ...
var match = new Array('iDEAL' , 'Sofortbanking' , 'Bancontact / MisterCash');
var found = false;
for(var i=0;i<3;++i){
    if(html.indexOf(match[i])!=-1){
        found = true;
    }
}
//use `found`

Here's my try on it. 这是我的尝试。

 var html, salient; html = $("li.woocommerce-order-overview__payment-method.method").html(); salient = [ "iDEAL", "Sofortbanking", "Bancontact / MisterCash" ]; for (i = 0; i < salient.length; i++) { if (html.indexOf(salient[i]) !== -1) { // it contains string i } } 

Or, if you want to use a RegEx, which is not necessarily better: 或者,如果您想使用RegEx,则不一定更好:

 var html; html = $("li.woocommerce-order-overview__payment-method.method").html(); if (html.match(/(?:iDEAL|Sofortbanking|Bancontact.*MisterCash)/)) { // it contains one of those strings } 

If you want to get the Stein which is present, Use match function. 如果要获取存在的Stein,请使用match功能。

If you just want to check whether it is there or not, then use the test in JavaScript 如果您只想检查它是否存在,请在JavaScript中使用test

/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/.test(
      jQuery('li.woocommerce-order-overview__payment-method.method')[0].innerHTML);

The regular expression 正则表达式

/(iDEAL|Sofortbanking|Bancontact|MisterCash){1,}/

Will match 1 or more occurances of that words 将匹配该单词的1个或多个出现

You can use an array of needles, and then Array.some to check if the element contains any of them 您可以使用针阵列,然后使用Array.some检查元素是否包含其中的任何一个

let needles  = ['iDEAL', 'Sofortbanking', 'Bancontact', 'Bancontact / MisterCash'];
let haystack = $('li.woocommerce-order-overview__payment-method.method').html();
let result   = needles.some( needle => haystack.includes( needle ) );

The || || (Or operator) does not work that way, I would suggest using the || (或运算符)不能那样工作,我建议使用|| outside of indexOf() Like so 在indexOf()之外像这样

indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1 indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1 Have a Look at a similar answer here indexOf('iDEAL') > 1 || indexOf('Sofortbanking') > 1 || indexOf('...')>1 在这里看看类似的答案

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

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