【问题标题】:how to check if there are same consecutive elements in a string or html如何检查字符串或html中是否有相同的连续元素
【发布时间】:2016-12-06 17:21:57
【问题描述】:

假设我有这个字符串

<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;
}

【问题讨论】:

  • 是的。一个好的起点通常是网络搜索stackoverflow.com/questions/28654091/… - 如果您失败了,那么您将在这里发布代码并寻求帮助,因为不幸的是,SO 不是请求代码的地方,而是寻求现有代码帮助的地方。所以,如果你不尝试任何事情,你得到你想要的东西的机会是有限的。

标签: javascript jquery


【解决方案1】:

原版 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>

【讨论】:

    【解决方案2】:

    你可以通过.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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2014-01-18
      相关资源
      最近更新 更多