假设我有这个字符串
<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”元素以及它们是否是连续的 sibling 。
chConImg = checkConsecutiveImg(strHtml) //true
chConImgFalse = checkConsecutiveImg(strHtmlFalse) //false
checkConsecutiveImg(str){
if(consecutive img elements are found)
return true;
else
return false;
}
最佳答案
普通 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>
关于javascript - 如何检查字符串或html中是否有相同的连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001246/