如何根据用户点击链接/按钮的情况将其重定向到不同的地址



为了简单起见,我有一个包含以下项目的菜单"W"X〃"Y";以及";Z";。无论用户是谁,每个项目都会重定向到网站上的不同页面。但我想要项目";Z";特别是根据用户重定向到不同的页面。例如,如果用户";1〃;点击";Z";,则他将被重定向到页面CCD_ 1。如果是用户";2〃;谁点击";Z";,则他将被重定向到CCD_ 2。等等

类似于:

  • if user = user1, then button_Z = <p><a href="http://reddit.com/">Z</a></p>

  • if user = user2, then button_Z = <p><a href="http://youtube.com/">Z</a></p>

User1被重定向到reddit,而user2被重定向到YouTube。

看起来您想要在url中进行一些非常简单的字符串连接。这里有一个简单的例子来展示你想要实现的目标。最有可能的是,您希望将这些变量从全局范围中移除,并接受它们作为函数的参数,或者使用某种状态管理。

let user = ''
document.querySelector('#username').addEventListener('change',updateUser)
function updateUser(e) {
user = e.target.value
}
document.querySelector('#dropdown').addEventListener('change',redirect)
function redirect(e) {
const selection = e.target.value;

if (selection === 'Z') {
console.log(`mywebsite.com/${selection}${user}`)
// window.location.replace(`mywebsite.com/${selection}${user}`)
} else {
console.log(`mywebsite.com/${selection}`)
// window.location.replace(`mywebsite.com/${selection}`)
}
}
<input id="username" />
<select id="dropdown">
<option>W</option>
<option>X</option>
<option>Y</option>
<option>Z</option>
</select>

最新更新