我可以在循环中更改索引吗?

Can I change an index in a loop?

我有一系列 <div>s,每个都有一个颜色名称的 id,例如 <div id="white"></div>,它加载一个音频文件并用从ajax 单击 div 时调用

HTML

<audio id="song" preload="none">
</audio>
<div id="white"></div>
<div id="pink"></div>
<div id="play" onclick="document.getElementById('song').play()"></div>
<div>
  <h2 id="title"></h2>
  <h3 id="artist"></h3>
</div>`  

Javascript

$("#white").click(function(){
    $("#song").attr('src',data[0].songSrc);
    $("h2").html(data[0].title)
    $("h3").html(data[0].artist)
}); 

$("#pink").click(function(){
    $("#song").attr('src',data[1].songSrc);
    $("h2").html(data[1].title)
    $("h3").html(data[1].artist)
}); 

我可以使用 for 循环或 $.each 而不是重复相同的代码并手动更改 19 个项目中每个项目的 div id 和项目索引吗?

这是我正在处理的垃圾箱:jsbin

相关HTML:

<div id="play" onclick="document.getElementById('song').play()"></div>

我不完全确定你想要什么,但这应该能让你朝着正确的方向前进。

Html

<div id="content">
  <audio id="song" preload="none"></audio>
</div>
<div class="songs"></div>

然后 Javascript/jQuery

var html = '';
//Create a div for each fetched song
$.each(data, function(index,item){
  html += '<div class="song" data-song-id="'+index+'" data-artist="'+item.artist+'" data-src="'+item.songSrc+'"></div>';
});
// and add them to the div element with the class songs
$('.songs').html(html);

//Listen to clicks on all divs with the class song
$('.songs').on('click', '.song' function(e){
  var $this = $(this);
  var songId = $this.data('song-id');
  var artist = $this.data('artist');
  var src = $this.data('src');
  $("#song").attr('src',src);
})

是的,你可以。您必须同时重构 html 和 js。 在 HTML 处,您必须替换静态的 div,即具有 ID 的那些。取而代之的是,使用一个将附加所有歌曲的容器。

在 JS 中,为每首歌曲创建 DOM 个元素,并将其附加到歌曲容器中。在此之前,请确保所有元素都具有 "click" 带有歌曲特定数据的事件处理程序。趁着'bind'

HTML

  <div class="songs"></div>

  <div id="play" onclick="document.getElementById('song').play()"></div>
  <div>
    <h2 id="title"></h2>
    <h3 id="artist"></h3>
  </div> 
</div> 

JS

myUrl='http://meyecare.herokuapp.com/api/v1/songs';
$(window).load(function(){
  $.ajax({ 
    url: myUrl,
    type: 'GET',
    dataType: 'jsonp',
    success: function(data) {
      $.each(data, function(index,item){
        var element = $( "<div id='" + item.color + "'></p>" );
        element.on('click', function(){
          $("#song").attr('src',this.songSrc);
          $("h2").html(this.title);
          $("h3").html(this.artist);
        }.bind(item)); 
        element.appendTo(".songs");    
      }); 
    }, 
    error: function(){
      console.log('Shnope!');
    },
  });
});

为什么不给所有颜色一个通用的 class,然后将对象索引存储在数据属性中。然后您只需单击一次即可填充正确的数据。像这样:

$("div.color").click(function(){
  var index = $(this).data('src');
  $("#song").attr('src',data[index].songSrc);
  $("h2").html(data[index].title);
  $("h3").html(data[index].artist);
}); 
<div id="white" class="color" data-src="0"></div>
<div id="pink" class="color" data-src="1"></div>