如何检查字符串或html中是否有相同的连续元素

时间:2016-12-06 17:21:57

标签: javascript jquery

假设我有这个字符串

<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 个答案:

答案 0 :(得分:2)

香草Javascript方法

&#13;
&#13;
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')}`);
&#13;
<div id="ch">abcdefg<img /><img />hij</div>
<div id="ad">abc<img />defg<img />hij</div>
&#13;
&#13;
&#13;

jQuery方法

&#13;
&#13;
$(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')}`);
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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>