2017-08-08 1 views
0

私は自分のページに6枚の画像アップロードを持ち、新しい画像が選択されたときに画像プレビューを更新するスクリプトを持っています。私はスクリプトごとにidを変更した6つのスクリプトを持っているとは思っていないので、javascriptのnoobとしてこれをどのように達成するのかと思っていました。同様の要素idをループして情報を変更/更新するには?

各画像のアップロードIDはlogo-id-#です。

ブートストラップイメージのアップロード:

<div class="col-md-2"> 
    <div class="form-group"> 
      <div class="main-img-preview center"> 
       <img class="thumbnail img-preview" src="http://farm4.static.flickr.com/3316/3546531954_eef60a3d37.jpg" title="Preview Logo"> 
      </div> 
      <div class="input-group"> 
       <input id="fakeUploadLogo" class="form-control fake-shadow" placeholder="Choose File" disabled="disabled"> 
         <div class="input-group-btn"> 
          <div class="fileUpload btn btn-primary fake-shadow"><span><i class="glyphicon glyphicon-upload"></i> Browse</span> 
           <input id="logo-id-1" name="logo" type="file" class="attachment_upload"> 
          </div> 
         </div> 
      </div> 
    </div> 

Javascriptを:

<script> 
$(document).ready(function() { 
    var brand = document.getElementById('logo-id-1'); 
    brand.className = 'attachment_upload'; 
    brand.onchange = function() { 
     document.getElementById('fakeUploadLogo').value = this.value.substring(12); 
    }; 

    // Source: http://stackoverflow.com/a/4459419/6396981 
    function readURL(input) { 
     if (input.files && input.files[0]) { 
      var reader = new FileReader(); 

      reader.onload = function(e) { 
       $('.img-preview').attr('src', e.target.result); 
      }; 
      reader.readAsDataURL(input.files[0]); 
     } 
    } 
    $("#logo-id-1").change(function() { 
     readURL(this); 
    }); 
}); 

+1

'$(" [id^= 'logo-id - '] ")'を使ってみてください。参照してください:---------- https://stackoverflow.com/questions/13541898/how-can-i-select-an-element-by-id-with-jquery-using-regex – iavery

+0

https: //jsfiddle.net/g006hhg3/ – adeneo

答えて

0

各反復で、ループ内で全体を包みます別のIDを指定してIDを増やします。

$(document).ready(function() { //note - can be shortened to $(function() { 
    for (var i=1; i<=6; i++) { 
     //...your code. From now on, refer not to 'logo-id-1' but to 'logo-id-'+i 
    } 
}); 
関連する問題