简体   繁体   English

使用 jQuery 或 JS 中的 URL 参数中的值更新图像?

[英]Update an image using with value from a URL parameter in jQuery or JS?

What I'm trying to do is getting a JS parameter to replace an image SRC with a custom URL using a URL parameter.我想要做的是获取一个 JS 参数,使用 URL 参数用自定义 URL 替换图像 SRC。

Example of parameter:参数示例:

https://example.com?i=https://example.com/img.jpg

There are a few ways to do this and I hope this gets you started (I have not tested this code):有几种方法可以做到这一点,我希望这能让你开始(我没有测试过这段代码):

function getUrlVars () {
    let vars = {};
    const p = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,k,v) {
      vars[k] = v;
    });
    return vars;
}

const src = getUrlVars('i');
const img = document.getElementById('image-id-here');
img.src = src;

The getUrlVars is a generic function I often use. getUrlVars是我经常使用的通用 function。 It's likely more complicated than what you need.它可能比您需要的更复杂。

A word of waring;一句警告; you should do the extra work/research to validate the content of the URL parameter before inserting into into your page.在插入页面之前,您应该进行额外的工作/研究以验证 URL 参数的内容。

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

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