如何通过id检索动态数量的元素

时间:2017-10-20 08:51:33

标签: javascript jquery

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

<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等。以这种方式看起来并不干净。有人可以指导我解决这个问题吗?

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

不是通过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...
});

答案 2 :(得分:0)

let elements = document.querySelectorAll('[id^=sing-mobile-]');

for (let elem of elements) {
    var initializeSignpostCarousel = sequence(elem, options);
}