最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How can I replace image with javascript? - Stack Overflow

programmeradmin0浏览0评论

My view like this :

<li id="thumbnail-view" class="count-photo">
    <div class="thumbnail">
        <img src="{{ asset('img/thumbs/'.$photo) }}" alt="">
        <a href="javascript:" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
        <ul class="list-inline list-edit">
            ...
        </ul>
    </div>
</li>

My javascript like this :

var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

My view like this :

<li id="thumbnail-view" class="count-photo">
    <div class="thumbnail">
        <img src="{{ asset('img/thumbs/'.$photo) }}" alt="">
        <a href="javascript:" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
        <ul class="list-inline list-edit">
            ...
        </ul>
    </div>
</li>

My javascript like this :

var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

Share Improve this question edited Jun 8, 2017 at 10:04 drmonkeyninja 8,5404 gold badges34 silver badges59 bronze badges asked Jun 8, 2017 at 10:03 samuel tohsamuel toh 7,08624 gold badges76 silver badges110 bronze badges 3
  • 2 use .attr("src", "linkhere") – guradio Commented Jun 8, 2017 at 10:04
  • I don't think your question is clear enough!"{{ asset('img/thumbs/'.$photo) }}" is like a template, i think you must follow the template Convention – alalalala Commented Jun 8, 2017 at 10:14
  • Just use attr. Its a jquery function. You can set or get any attribute of a selected element. – Rudraksh Pathak Commented Jun 8, 2017 at 10:15
Add a ment  | 

3 Answers 3

Reset to default 5

Simple way

 var photo = 'flower.jpg';
 $('#thumbnail-view img').attr('src', photo);

Don't set the inner HTML of an image, set its src property.

$('#thumbnail-view img').prop("src", "{{ asset('img/thumbs/') }}"+photo);

Sidenote: if this is in a .js file then your template engine probably will not process the asset tag so you need to hardcode the path or grab it from elsewhere.

$('#thumbnail-view img').prop("src", "/assets/img/thumbs/"+photo);

You should use like this: $('#thumbnail-view img').attr('src','path/to/photo');

发布评论

评论列表(0)

  1. 暂无评论