如何设置img标签的src?

时间:2022-11-27 18:27:31

I have a javascript function that is getting the values of other html elements and I want to pass those values to the image tag. How do I Pass that?

我有一个javascript函数,它获取其他html元素的值,我想将这些值传递给图像标记。我该如何通过?

My Function is below:

我的功能如下:

<script type="text/javascript">
    function submitValues()
    {
        var firstname = document.getElementsByName("firstname")[0].value;
        var lastname = document.getElementsByName("lastname")[0].value;
    }

<img src="firstname=get_javascript_valuehere;lastname=get_javascript_valuehere;/>

3 个解决方案

#1


Put an id on your image tag and use the following:

在您的图片代码上添加ID并使用以下内容:

document.getElementById("myImg").src = "firstname=" + firstname + ";lastname=" + lastname + ";";

That's at least what you've asked for, but I imagine there is more to this question if you'd like to elaborate.

这至少是你所要求的,但我想如果你想详细说明这个问题还有更多。

#2


Use jQuery's .attr() method to modify the attribute of an element.

使用jQuery的.attr()方法修改元素的属性。

function submitValues() {
    var firstname = $("[name=firstname]").val();
    var lastname = $("[name=lastname]").val();
    $("img").attr("src", "firstname=" + firstname + ";lastname=" + lastname + ";");
});

#3


function submitValues()
{
    var firstname = document.getElementsByName("firstname")[0].value;
    var lastname = document.getElementsByName("lastname")[0].value;
    var img =  document.getElementById('fullName');
    img.setAttribute("src","firstname"+firstname+"lastname"+lastname+";");      
}

Add an id to the img to query it using the document.getElementById(), then set the src attribute using this code.

向img添加一个id,使用document.getElementById()查询它,然后使用此代码设置src属性。

It should work.

它应该工作。

#1


Put an id on your image tag and use the following:

在您的图片代码上添加ID并使用以下内容:

document.getElementById("myImg").src = "firstname=" + firstname + ";lastname=" + lastname + ";";

That's at least what you've asked for, but I imagine there is more to this question if you'd like to elaborate.

这至少是你所要求的,但我想如果你想详细说明这个问题还有更多。

#2


Use jQuery's .attr() method to modify the attribute of an element.

使用jQuery的.attr()方法修改元素的属性。

function submitValues() {
    var firstname = $("[name=firstname]").val();
    var lastname = $("[name=lastname]").val();
    $("img").attr("src", "firstname=" + firstname + ";lastname=" + lastname + ";");
});

#3


function submitValues()
{
    var firstname = document.getElementsByName("firstname")[0].value;
    var lastname = document.getElementsByName("lastname")[0].value;
    var img =  document.getElementById('fullName');
    img.setAttribute("src","firstname"+firstname+"lastname"+lastname+";");      
}

Add an id to the img to query it using the document.getElementById(), then set the src attribute using this code.

向img添加一个id,使用document.getElementById()查询它,然后使用此代码设置src属性。

It should work.

它应该工作。