开发者

using jquery contains inside a function?

I'm trying to use the jquery :contains (or .contai开发者_Go百科ns()) selector inside a function, however I can't seem to get it to work.

Basically I'm passing a string to a function and I want to check the variable if it contains X, do something else do something else. If that makes sense.

Here's my code.

function checkMe(myVar) {
  if ($(myVar).contains("foo")) {
    //do something
  } else {
    //do something else
  }
}

and my call to the function:

checkMe("/foo/bar");

But it's not working. Any help would be appreciated! :)


The jQuery contains function checks if a dom node contains another dom node. What you are wanting to do is just check to see if a string is contained inside another. You could do a simple regex search for this.

Try this instead:

if (myVar.match("foo")) {


hi just check the jquery api http://api.jquery.com/jQuery.contains/ , jquery.contains is applied to DOM element. if you want to do string contains, try:

/foo/i.test("foo/bar");


contains checks if one DOM element contains another.

For what you want, you don't need jQuery at all:

function checkMe(myVar) {
  if (myVar.indexOf("foo") >= 0) {
    //do something
  } else {
    //do something else
  }
}

indexOf will return -1 if "foo" is not found in the passed string; otherwise it returns the index in the string where "foo" was found.


do you have to use jquery? what about something like this?

function checkMe(myVar) {
  if (myVar.indexOf("foo") > -1) {
    //do something
  } else {
    //do something else
  }
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜