【问题标题】:How to loop through similar element id's to change / update info?如何遍历相似的元素 id 来更改/更新信息?
【发布时间】:2018-01-16 07:57:47
【问题描述】:

我的页面上有 6 张图片上传,并且有一个脚本可以在选择新图片时更新图片预览。我不想有 6 个脚本,每个脚本只有一个更改的 id,所以我想知道作为一个 javascript 菜鸟我​​将如何实现这一点。

每张图片上传的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);
    });
});

【问题讨论】:

标签: javascript jquery twitter-bootstrap


【解决方案1】:

将整个事物包装在一个循环中,每次迭代都针对不同的(并且递增的 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
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多