2016-12-06 85 views
1

相同的連續元素比方說,我有這個字符串如何檢查是否有一個字符串或HTML

<div id="ch">abcdefg<img /><img />hij</div> 
<div id="ad">abc<img />defg<img />hij</div> 

strHtml = $('div#ch').html(); 
strHtmlFalse = $('div#ad').html(); 

現在是有可能的方式來檢查,如果兩個「IMG」的元素被發現,如果他們連續的兄弟姐妹。

chConImg = checkConsecutiveImg(strHtml) //true 
chConImgFalse = checkConsecutiveImg(strHtmlFalse) //false 


checkConsecutiveImg(str){ 
    if(consecutive img elements are found) 
     return true; 
    else 
     return false; 
} 
+2

是的,有。一個好的起點往往是網絡搜索http://stackoverflow.com/questions/28654091/javascript-function-to-automatically-count-consecutive-letters-in-a-string - 如果你失敗了,那麼你將得到代碼在這裏張貼並尋求幫助,不幸的是,SO不是申請代碼的地方,而是尋求現有代碼的幫助。所以如果你沒有嘗試任何事情,你得到你想要的東西的機會是有限的。 – GillesC

回答

2

香草JavaScript方式

function checkConsecutiveImage(str) { 
 
    const parent = document.querySelector(str); 
 
    const children = parent.children; 
 
    const image = Array.from(children).find(elem => elem.tagName === 'IMG'); 
 
    
 
    return image.nextSibling.nodeType === 1 && image.nextElementSibling.tagName === 'IMG' 
 
} 
 

 
console.log(`Consecutive images in #ch: ${checkConsecutiveImage('#ch')}`); 
 

 
console.log(`Consecutive images in #ad: ${checkConsecutiveImage('#ad')}`);
<div id="ch">abcdefg<img /><img />hij</div> 
 
<div id="ad">abc<img />defg<img />hij</div>

jQuery的方法

$(function() { 
 
    function checkConsecutiveImg(str) { 
 
    const $img = $(str).find('img'); 
 
    
 
    return $img[0].nextSibling.nodeType === 1 && $img.next().is('img'); 
 
    } 
 

 
    console.log(`Consecutive images in #ch: ${checkConsecutiveImg('#ch')}`); 
 

 
    console.log(`Consecutive images in #ad: ${checkConsecutiveImg('#ad')}`); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="ch">abcdefg<img /><img />hij</div> 
 
<div id="ad">abc<img />defg<img />hij</div>

1

您可以用功能.contents().is()實現它。

function checkConsecutiveImg(parent) { 
 
    const children = parent.contents(); // e.g. ["abcdefg", <img>, <img>, "hij"] 
 
    let containsConsecutives = false; 
 
     
 
    children.each((index, currentElement) => { 
 
     if ($(currentElement).is('img') && $(children[index - 1]).is('img')) { 
 
      containsConsecutives = true; 
 
     } 
 
    })  
 
     
 
    return containsConsecutives; 
 
} 
 

 
console.log(checkConsecutiveImg($('div#ch'))) 
 
console.log(checkConsecutiveImg($('div#ad')))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="ch">abcdefg<img /><img />hij</div> 
 
<div id="ad">abc<img />defg<img />hij</div>

相關問題