简体   繁体   中英

how to clone url parameter value inside img src attribute?

I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.

I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:

<img id="target" src="images/">samplevalue.png</img>

I need to do like it this:

<img id="target" src="images/samplevalue.png" />

Sample parameter: param1=samplevalue.png

here's the code:

html

<div id="block1"></div>
<img id="target" src=""/>

jQuery/Javascript

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return decodeURIComponent(pair[1].replace(/\+/g, "&nbsp"));
        }
    }
    return decodeURIComponent(pair[1]);
}

document.getElementById("block1").innerHTML = 
getQueryVariable("param1");

$(document).ready(function() {
    $("img#target").attr("src", "images/").html($("#block1").html());
});

Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.

Any help on this is highly appreciated. Thank you very much in advance.

You should do it like this :

$(document).ready(function() {
    var param1 = getQueryVariable("param1");
    $("img#target").attr("src", "images/"+param1);
    $("#block1").html(param1);  
});

Put your param into a variable and then use it to change your SRC attribute and to put the content into your div.

You have to add the returned value from the function as part of the attribute src .

With .html($("#block1").html()) on the image element, you are trying to set html on th image which is actually invalid:

Change the function to:

$(document).ready(function() {
  var urlPart = getQueryVariable();
  $("img#target").attr("src", "images/" + urlPart);
});

Please Note:

Since you are already using jQuery, I will suggest you not to mix JavaScript & jQuery if possible, like:

document.getElementById("block1").innerHTML = getQueryVariable("param1");

Could be easily written:

$('#block1').text(getQueryVariable("param1")); //text() is preferred when dealing with text content 
$("img#target").attr("src", "images/"+$("#block1").html());

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