如何用javascript替换图像?

时间:2022-11-25 14:50:32

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 :

我的javascript是这样的:

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

如果执行了javascript代码,我想更改图像

I try like that, but it does not work

我尝试这样,但它不起作用

How can I do it?

我该怎么做?

3 个解决方案

#1


2  

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

不要设置图像的内部HTML,设置其src属性。

$('#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.

旁注:如果这是在.js文件中,那么您的模板引擎可能不会处理资产标签,因此您需要对路径进行硬编码或从其他地方获取。

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

#2


5  

Simple way

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

#3


1  

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

你应该这样使用:$('#thumbnail-view img')。attr('src','path / to / photo');

#1


2  

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

不要设置图像的内部HTML,设置其src属性。

$('#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.

旁注:如果这是在.js文件中,那么您的模板引擎可能不会处理资产标签,因此您需要对路径进行硬编码或从其他地方获取。

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

#2


5  

Simple way

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

#3


1  

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

你应该这样使用:$('#thumbnail-view img')。attr('src','path / to / photo');