2017-07-01 70 views
0

我想在上傳前預覽圖像。在我的情況下,它有一點輸入標籤,如果我使用屬性來捕捉節點和設置值,所有節點將顯示相同的圖片。如何獲取兄弟節點並設置javascript更改事件的值?

 @foreach($products as $item) 
     <tr> 
      <th><input class='imgInp' type="file" name="icon"/><img src ='' alt="" class='thumb'/></th> 
     </tr> 
     @endforeach 

我嘗試使用event.target(輸入)搭上兄弟節點(IMG)和設定值,但它不能正常工作

function readURL(input){ 
    if(input.files && input.files[0]){ 
     var reader = new FileReader(); 
     reader.onload = function(e){ 
      $(e).next().attr('src', e.target.result);  
     }; 
     reader.readAsDataURL(input.files[0]); 
    } 
} 
$('.imgInp').change(function(){ 
    readURL(this); 
}); 

回答

1

你的問題是在這條線:

$(e).next().attr('src', e.target.result); 

將其更改爲:

$(input).next().attr('src', e.target.result); 

此外,我假設你正在將行添加到表體中。所以,用td改變th元素。

function readURL(input){ 
 
    if(input.files && input.files[0]){ 
 
     var reader = new FileReader(); 
 
     reader.onload = function(e){ 
 
      $(input).next().attr('src', e.target.result); 
 
     }; 
 
     reader.readAsDataURL(input.files[0]); 
 
    } 
 
} 
 

 
$('.imgInp').change(function(){ 
 
    readURL(this); 
 
});
.thumb { 
 
    width: 100px; 
 
    height: 100px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td><input class='imgInp' type="file" name="icon"/><img src='' alt="" class='thumb'/></td> 
 
    </tr> 
 
    <tr> 
 
     <td><input class='imgInp' type="file" name="icon"/><img src='' alt="" class='thumb'/></td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+0

THX這對我很有幫助。 –

相關問題