简体   繁体   中英

How do I add the parameter of a javascript function into a url?

Say I have a function:

function potato(param) {
document.body.style.backgroundImage = 'url(file:///C:/Users/Joe)';}

and I want to make it so when I call potato('/chicken.jpg'), it will modify the url in potato to be file:///C:/Users/Joe/chicken.jpg. How could this be done? Thank you

Javascript in a browser doesn't have access to the file system. Try running a local web browser with a document root of C:\\User\\Joe and then pass in the url path ... something like ' http://localhost/chicken.jpg '

Just use concatenate operator. So in JavaScript use +.

'my/base/url' + myStringVar;

'url(file:///C:/Users/Joe'+param+')';

I think you want something like this. This code will replace the background image when you call the function with the param :

function potato(param){
  var $element = document.querySelector('.something'),
      url = 'file:///C:/Users/Joe/' + param;

  $element.style.backgroundImage = "url('" + url + "')";

  console.log('=>' + $element.style.backgroundImage);
}

This is live example on jsbin => https://jsbin.com/?html,console,output

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