【问题标题】:How to retrieve a dynamic number of elements by id [duplicate]如何通过id检索动态数量的元素[重复]
【发布时间】:2018-04-01 09:59:19
【问题描述】:

我想知道是否有更好的方法使这些手工编码的函数调用动态化?

<div id="sing-mobile-1">.....</div>
<div id="sing-mobile-2">.....</div>
var signCarousel1 = document.getElementById("sing-mobile-1");
var signCarousel2 = document.getElementById("sing-mobile-2");

if (signCarousel1) {
  var initializeSignpostCarousel = sequence(signCarousel1, options);
}
if (signCarousel2) {
  var initializeSignpostCarousel = sequence(signCarousel2, options);
}

也可能有#sign-mobile-3#sign-mobile-4等,这样看起来不干净。有人可以指导我解决这个问题吗?

【问题讨论】:

  • 给那些元素通用类名,这样遍历它们会更容易。

标签: javascript jquery


【解决方案1】:

不要通过id 获取不确定数量的元素,而是对它们全部使用一个类。然后,您可以遍历该类的所有元素并调用您的函数:

<div class="sing-mobile">...</div>
<div class="sing-mobile">...</div>
document.querySelectorAll('.sing-mobile').forEach(function(el) {
  var initializeSignpostCarousel = sequence(el, options);
  // work with initializeSignpostCarousel here...
});

或者在 jQuery 中:

$('.sing-mobile').each(function() {
  var initializeSignpostCarousel = sequence(this, options);
  // work with initializeSignpostCarousel here...
});

【讨论】:

  • NodeList.prototype.forEach 是 NodeLists 的一个相当新的补充。 Internet Explorer 和 Edge 根本不支持它。但是可以使用Array.prototype.slice.call(nodeList) 将 NodeLists 转换为数组。
  • @AndreasLinnert 看起来它应该适用于 IE8 和 IE9 文档:developer.mozilla.org/en-US/docs/Web/API/Document/…
  • @MasterYoda Andreas 正在谈论nodeList.forEach(),并且是正确的。这是一个很好的观点,还有workarounds - 我只是渴望有一段时间我们不会被 IE 阻碍:)
  • @RoryMcCrossan 很公平,对造成的误解表示歉意。
  • @RoryMcCrossan - 此解决方案用于显示滑块元素。但是,滑块自动滑动没有按预期工作。
【解决方案2】:

您可以使用通配符^ 来执行此操作

function getElem() {

  // ^ is a wildcard which will pick all elements whose id starts with sing-mobile-1
  $el = $("[id^=sing-mobile-]");
  if ($el.length == 0)
    return false;


  var initializeSignpostCarousel = sequence($el[0], options);
  return initializeSignpostCarousel;
}

【讨论】:

    【解决方案3】:
    let elements = document.querySelectorAll('[id^=sing-mobile-]');
    
    for (let elem of elements) {
        var initializeSignpostCarousel = sequence(elem, options);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多