简体   繁体   中英

Create a query string in a URL (for a link <a>)

I am trying to create a query string in a URL for a link. I can't find what is the problem, I tried a lot of thing but I always get an "undefined" for "urlCameras". thanks for your help !

 const cameras = [{ _id: "Camera 1" }]; const linkProduct = document.getElementById("linkProduct"); let url = 'file:///D:/openclassrooms/projet5/orinoco/product.html'; let urlObj = new URL(url); let params = new URLSearchParams(url.search); let idCameras = cameras[0]._id; let urlCameras = params.append("?id=", "idCameras"); linkProduct.href = urlCameras;
 <a id="linkProduct">Click</a>

Several things

  1. .append("?id=", "idCameras"); should be .append("id",idCameras) because
  • ? and = - searchParams handles that for you
  • don't quote the parameter variable
  1. You have too many vars - the URL has its own searchParams you can use

 const cameras = [{ _id: "Camera1" }]; const linkProduct = document.getElementById("linkProduct"); let url = 'file:///D:/openclassrooms/projet5/orinoco/product.html'; let urlObj = new URL(url); let idCameras = cameras[0]._id; urlObj.searchParams.append("id", idCameras); linkProduct.href = urlObj;
 <a id="linkProduct">Click</a>

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