2014-01-16 17 views
0
<div id='QuestionText'> 
    <p>This is a simple example </p> 
    <span> I am asking the question </span> 
</div> 

我得到div的HTML內容在下面的行如何檢查是否選擇存在於跨度或不jQuery的

VAR existing_lesson = $( '#QuestionText')。HTML ();

我得到了 '問題' 作爲我在下面一行

VAR getselectedarea = $ .selection()選擇;

現在我想要找的選擇是否是存在於span元素或者不意味着如果我選擇simple example爲我的選擇,我應該得到,這是存在於HTML標籤,如果我選擇the question我的選擇我應該知道它存在於哪個html標籤中。

回答

1
var foundInSpan = $("#QuestionText > span").text().indexOf(text) > -1; 

var foundInP = $("#QuestionText > p").text().indexOf(text) > -1; 

,或者您可以使用grep找到所有包含該文本的標籤:

var tags = $("#QuestionText").children().grep(
    function(){ 
     return $element.text().indexOf(text) > -1; 
    }); 
+1

爲什麼在這種情況下不使用「:contains」語句?性能問題? – cubitouch

0

另一種方式來做到這一點(以替代獵人的indexOf做法)是一個正則表達式.test()

var foundInSpan = new RegExp(text).test($("#QuestionText > span").text()); 

jsPerf顯示的性能是更多或少洗:http://jsperf.com/find-text-test

相關問題