简体   繁体   中英

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. 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

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.

EDIT

Drainage and Electrics are modal links that when clicked show a list of towns pulled from a database.

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.

I'm not sure if the function setAttribute exists but you could try this instead:

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. You should have area in $conn variable when page loaded.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM