![](/img/trans.png)
[英]how to retrieve href value for an onclick event based on “class” selector in Javascript?
[英]onClick set href value based on what was clicked
当我将属性设置为 href 时,我正在尝试找到一种显示 PHP 的方法。 这就是我到目前为止所拥有的。
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/' );};}
面积 = 英国不同的城镇
所以我的 url 应该显示为 www.example.co.uk/Drainage/Bristol
到目前为止,它显示为 Drainage 或 Drainage/Undefined 不确定这是否是实现我想要的最佳方式,但我已经尝试了一段时间并决心让它发挥作用。
编辑
Drainage 和 Electrics 是模态链接,单击时会显示从数据库中提取的城镇列表。
例子
如果点击了排水系统,那么城镇将加载,然后用户可以 select 列表中的一个城镇,然后该城镇应路由到该城镇页面,但 URL 应设置为排水/动态城镇,因为点击了排水链接。
我不确定 function setAttribute
是否存在,但你可以试试这个:
window.onload = function() {
document.getElementById('drainage').onclick = function() {
document.getElementById("link").href="YOUR_NEW_LINK";
}
//Do that for the second button aswell
}
首先有语法错误:
document.getElementById('link').setAttribute( 'href', 'Drainage/' <?php echo $conn["area"]; ?> );
应该:
document.getElementById('link').setAttribute( 'href', 'Drainage/<?php echo $conn["area"]; ?>');
其次,如果您在页面加载时加载 area($conn["area"]) ,则可以实现它。 加载页面时,您应该在 $conn 变量中有区域。
像这样:
<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.