简体   繁体   English

如何克隆img src属性中的url参数值?

[英]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. 我试图从url中获取参数值,将其添加到div中,然后在img src属性中克隆该值。

I can get the parameter value inside a div, and get it to clone as well but it's doing it like this: 我可以在div内获取参数值,也可以将其克隆,但这是这样的:

<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 样本参数: param1=samplevalue.png

here's the code: 这是代码:

html HTML

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

jQuery/Javascript 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. 即使直接在img src属性中添加参数值也比在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. 将参数放入变量中,然后使用它来更改SRC属性并将内容放入div中。

You have to add the returned value from the function as part of the attribute src . 您必须将函数返回的值添加为属性src一部分。

With .html($("#block1").html()) on the image element, you are trying to set html on th image which is actually invalid: 使用image元素上的.html($("#block1").html()) ,您试图在实际上无效的图像上设置html:

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: 由于您已经在使用jQuery,因此建议您不要将JavaScript和jQuery混合使用,例如:

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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