This code:

if( $('span:contains("'+user_choice+'")').length == 0 )

uses the contain selector to find the <span>, which contains the user input. The user input user_choice is a number, like 1 or 23 or 31 etc.

But the code fails to find the specific <span>, since e.g. the user input user_choice = 1 will find both 1 and 21 and 31 and all numbers that contain 1. I need only to find the specific <span> that is exactly 1.

Is the contain selector wrong for this purpose and how can I correct it to make it work?

有帮助吗?

解决方案

Yes, the contains selector is wrong for your purpose. As the name suggests it matches any element that contains the specified text as a substring, not only those elements where there's an exact match.

You could try using .filter():

var matchingElements = $('span').filter(function(index) {
    return $(this).text() === user_choice;
});
if(matchingElements.length === 0) {
    ...
}

其他提示

You can use filter method.

var len = $('span').filter(function(){
     return $(this).text() == user_choice;
}).length;

How about something like this?

$('span').each(function(){
  if ($(this).html() == user_choice){
   return true;
  }
 });

Try with each function ,it will compare all the tags of "span"

$('span').each(function(){
  if ($(this).text() == "my_choosen_var"){
    return true;
  }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top