简体   繁体   中英

How to set the src of an img tag?

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?

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;/>

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

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.

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

function submitValues() {
    var firstname = $("[name=firstname]").val();
    var lastname = $("[name=lastname]").val();
    $("img").attr("src", "firstname=" + firstname + ";lastname=" + lastname + ";");
});
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.

It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM