[英]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.