2016-12-06 85 views
1

我已經創建了下面的函數,它搜索特定Word的主體,並且如果它存在或不存在,我將能夠獲得結果。但是如果它存在,我怎麼才能找到那個特定的對象並進行交互。根據對象中的文本獲取特定對象

(function ($) { 
 

 
    $.fn.WordBreaker = function (x) { 
 

 
     return this.each(function() { 
 

 
      var wrapper = $(this); 
 

 
      var xx = $.extend({ 
 
       words: "", 
 
      }, x || {}); 
 

 
      function initialized() { 
 
       xx.words.forEach(function (x, y) { 
 
        var lw, rw; 
 
        lw = x.toString().split(",")[0]; 
 
        rw = x.toString().split(",")[1]; 
 

 
        if ($("body:contains('" + lw + "')").length > 0) { 
 
         alert("I found an object that contains: " + lw + " , but how do i tager that object?") 
 
        } 
 

 
       }, xx.words) 
 
      } 
 
      initialized(); 
 
     }); 
 
    } 
 

 
}(jQuery)); 
 

 
var items = [ 
 
["THISISALONGTEXTTHATIWANTTOBREAK", "THIS-IS-A-LONG-TEXT-THAT-I-WANT-TO-BREAK"] 
 
]; 
 
$('.col-md-5').WordBreaker({ words: items })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="row"> 
 
      <div class="col-md-5" style="background: #00ffff"> 
 
       <h1>THISISALONGTEXTTHATIWANTTOBREAK</h1> 
 
      </div> 
 
     </div>

+0

那會是什麼具體的目標是什麼? DIV /跨度/連接/款/ ...?如果你知道它只是一個div,你可以搜索所有的div:$(div).each(function(){/ *搜索div的內容在這裏* /}); – Seb

+0

它可能是任何東西。任何可以包含文本基本的對象。但我希望它像動態一樣 –

+0

因此,它可能是一個圖像的替代文字?甚至在評論中?你可以嘗試使用正則表達式來讓標籤保持文本。 (但如果這是一個
,這將無濟於事。 – Seb

回答

1

對於這個答案,我從Using jQuery is there a way to find the farthest (deepest, or most nested) child element?採取的代碼,並把它放在這裏。原來的答案來自@Methos。

(function ($) { 
 

 
    $.fn.WordBreaker = function (x) { 
 

 
     return this.each(function() { 
 

 
      var wrapper = $(this); 
 

 
      var xx = $.extend({ 
 
       words: "", 
 
      }, x || {}); 
 

 
      function initialized() { 
 
       xx.words.forEach(function (x, y) { 
 
        var lw, rw; 
 
        lw = x.toString().split(",")[0]; 
 
        rw = x.toString().split(",")[1]; 
 
        var all_matched_elements = $(":contains('" + lw + "')"); 
 
        var all_parent_elements = $(all_matched_elements).parents(); 
 
        var all_deepest_matches = $(all_matched_elements).not(all_parent_elements); 
 

 
        console.log(all_deepest_matches); // this is an object containing the deepest objects that match the search string 
 

 
       }, xx.words) 
 
      } 
 
      initialized(); 
 
     }); 
 
    } 
 

 
}(jQuery)); 
 

 
var items = [ 
 
["THISISALONGTEXTTHATIWANTTOBREAK", "THIS-IS-A-LONG-TEXT-THAT-I-WANT-TO-BREAK"] 
 
]; 
 
$('.col-md-5').WordBreaker({ words: items })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="row"> 
 
      <div class="col-md-5" style="background: #00ffff"> 
 
       <h1>THISISALONGTEXTTHATIWANTTOBREAK</h1> 
 
      </div> 
 
     </div>