-1

文字列が要素内に含まれているかどうかを確認する方法はありますか?具体的にはリンク?

例えば:

<a href="#">Some text foo_string more text</a>

要素として「a」を返します。jQueryまたはPHP-関係ありません。ありがとうございました!

明確化:

私が知りたいのは、foo_stringを含む要素です。要素に文字列が含まれているかどうかではありません。

4

4 に答える 4

5

Checking if the element contains the string

To check if an element meets this criterion, try the jQuery contains selector:

if ($('#some-element').is(':contains("foo_string")')) {
    // Do something...
}

Note this selector is case-sensitive.


Selecting the element(s) that contain(s) the string

To select elements that meet this criterion, simply pass the selector as an argument to the main jQuery function as you would with any other selector:

var element_with_foo = $(':contains("foo_string")');

Remember it's recommended to limit the scope of the selection, otherwise it will apply to the entire DOM.

于 2013-03-18T14:27:16.203 に答える
2

using jquery

if($('a').text().length < 1 ){
   alert("empty")
}else{
  alert("not");
}

updated

$(":contains('Some text foo_string')"); //this get all the element with the text in it

u can use .prop('tagName') to get the tag name..

fiddle here updated fiddle here

于 2013-03-18T14:26:10.707 に答える
2

innerTextまたはtextContentDOMプロパティとJavaScriptの正規表現メソッドを使用できます。

例えば

var el = document.getElementById('my-link');
var txt = el.innerText;
return txt.match(/str/);

ここでjQueryを使用する方が簡単ですが、これは純粋なJavaScriptソリューションです。

于 2013-03-18T14:25:31.147 に答える
1

これを試して...

if ($('a').html().indexOf('foo_string') != -1) // doSomething

于 2013-03-18T14:26:03.700 に答える