在 URL 中创建查询字符串(对于 link <a>)
Create a query string in a URL (for a link <a>)
我正在尝试在 URL 中为 link 创建一个查询字符串。我找不到问题所在,我尝试了很多东西,但我总是得到“urlCameras”的“未定义”。感谢您的帮助!
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>
几件事
.append("?id=", "idCameras");
应该是 .append("id",idCameras)
因为
?
和 =
- searchParams 为您处理
- 不要引用参数变量
- 您的变量太多 - URL 有自己的搜索参数,您可以使用
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>
我正在尝试在 URL 中为 link 创建一个查询字符串。我找不到问题所在,我尝试了很多东西,但我总是得到“urlCameras”的“未定义”。感谢您的帮助!
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>
几件事
.append("?id=", "idCameras");
应该是.append("id",idCameras)
因为
?
和=
- searchParams 为您处理- 不要引用参数变量
- 您的变量太多 - URL 有自己的搜索参数,您可以使用
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>