[英]onClick set href value based on what was clicked
I am trying to find a way to display PHP when I setAttribute to a href.当我将属性设置为 href 时,我正在尝试找到一种显示 PHP 的方法。 This is what I have so far.
这就是我到目前为止所拥有的。
window.onload = function () {
document.getElementById('drainage').onclick = function () {
document.getElementById('link').setAttribute( 'href', 'Drainage/' <?php echo $conn["area"]; ?> );
};
document.getElementById('electrics').onclick = function () {
document.getElementById('link').setAttribute( 'href', 'Electrics/' );};}
Area = Different towns in UK面积 = 英国不同的城镇
So my url should show as www.example.co.uk/Drainage/Bristol所以我的 url 应该显示为 www.example.co.uk/Drainage/Bristol
So far it shows just as Drainage or Drainage/Undefined not sure if this is best way to achieve what I want but I have been trying for a while and determined to make it work.到目前为止,它显示为 Drainage 或 Drainage/Undefined 不确定这是否是实现我想要的最佳方式,但我已经尝试了一段时间并决心让它发挥作用。
EDIT编辑
Drainage and Electrics are modal links that when clicked show a list of towns pulled from a database. Drainage 和 Electrics 是模态链接,单击时会显示从数据库中提取的城镇列表。
EXAMPLE例子
If drainage was clicked then towns would load and user could then select a town from the list which should then route to that town page but URL should be set as drainage/dynamictown as the drainage link was clicked.如果点击了排水系统,那么城镇将加载,然后用户可以 select 列表中的一个城镇,然后该城镇应路由到该城镇页面,但 URL 应设置为排水/动态城镇,因为点击了排水链接。
I'm not sure if the function setAttribute
exists but you could try this instead:我不确定 function
setAttribute
是否存在,但你可以试试这个:
window.onload = function() {
document.getElementById('drainage').onclick = function() {
document.getElementById("link").href="YOUR_NEW_LINK";
}
//Do that for the second button aswell
}
First thing there is syntax error in:首先有语法错误:
document.getElementById('link').setAttribute( 'href', 'Drainage/' <?php echo $conn["area"]; ?> );
Should be:应该:
document.getElementById('link').setAttribute( 'href', 'Drainage/<?php echo $conn["area"]; ?>');
Second you can achieve it if you load area($conn["area"]) on page load.其次,如果您在页面加载时加载 area($conn["area"]) ,则可以实现它。 You should have area in $conn variable when page loaded.
加载页面时,您应该在 $conn 变量中有区域。
Like this:像这样:
<a id="link">Test</a>
<button id="drainage">click</button>
<button id="electrics">click</button>
<?php
$conn["area"] = "Bristol"; // comment this line when you have dynamically
?>
<script>
window.onload = function () {
document.getElementById('drainage').onclick = function () {
document.getElementById('link').setAttribute( 'href', 'Drainage/<?php echo $conn["area"]; ?>');
};
document.getElementById('electrics').onclick = function () {
document.getElementById('link').setAttribute( 'href', 'Electrics/' );
};
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.