【问题标题】:Loop through an array of DIvs and display their innerHTML as H Tags?循环遍历一组 DIv 并将它们的 innerHTML 显示为 H 标签?
【发布时间】:2020-04-01 14:03:00
【问题描述】:

对于每个这样的文本块:

<div class="articles-slider">
<div class="slick-slide"><div class="user-title">danny<div>...more DIVs....<ul class="socials">.... 
</ul><div>
<div class="slick-slide"><div class="user-title">jane<div>...more DIVs....<ul class="socials">.... 
</ul><div>
<div class="slick-slide"><div class="user-title">tom<div>...more DIVs....<ul class="socials">.... 
</ul><div>
<div>
  1. 循环遍历类“user-title”数组并提取其内部html。

    var theNames = [];
    jQuery('.user-title').each(function () {
        theNames.push(this.innerHTML);
    });
    
  2. 在 UL class="socials" 之前添加一个空的 H4 TAG。

    var theNames = [];
    jQuery(".socials").prepend('<H4 class="sr-only the_title"></H4>');
    jQuery('.user-title').each(function () {
        theNames.push(this.innerHTML);
    });
    

-寻求帮助-

  1. 将names.innerhtml分别添加到H4标签中。

    var theNames = [];
    var theNamesText = [];
    jQuery(".socials").prepend('<H4 class="sr-only the_title"></H4>');
    jQuery('.user-title').each(function () {    
        theNames.push(this.innerHTML);
    });
    

【问题讨论】:

  • 您好,我不确定您尝试实现什么,但下面可以帮助您:$('.user-title').each(function () { $(this).find("ul " ).prepend('

    '+ $(this).text() +'

    '); }); });

标签: jquery arrays loops for-loop


【解决方案1】:

看起来你把问题复杂化了。无需存储标题。根据您的代码,您应该能够找到一个容器元素,它是您希望使用的元素的父元素 ($container)。然后找到您需要使用的元素($userTitle$socials),如果存在,请添加您的 H4 和标题。

$('slick-slide').each(function() {
  var $container = $(this);
  var $userTitle = $container.find('.user-title');
  var $socials = $container.find('.socials');
  if ($userTitle.length == 1 && $socials.length == 1) {
    $socials.prepend('<H4 class="sr-only the_title">' $userTitle.innerHtml '</H4>');
  }
});

【讨论】:

    【解决方案2】:

    谢谢 altaf-khokhar 和 erik-philips:)

    行得通!

    $('.slick-slide').each(function() {
      var $container = $(this);
      var $userTitle = $container.find('.user-title');
      var $socials = $container.find('.socials');
      if ($userTitle.length == 1 && $socials.length == 1) {
      $socials.prepend('<H4 class="sr-only the_title">' + $userTitle.text() + '</H4>');
       }
    });
    

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2021-11-06
      • 2021-11-09
      • 1970-01-01
      • 2013-12-26
      • 2015-11-20
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多