简体   繁体   中英

Using JavaScript and PHP for the value of a href attribute

In my code bellow I would like to replace the string #customer with window.location.hash .

echo '<th><a href="?sort-by=email&order='. $this->order .'#customer">E-Mail</a></th>';

How would it be possible to mix JavaScript with PHP in my case?

This isn't really a matter of PHP.

Just remove the hash as it is right now in the PHP, then we can take it client-side and you can add it there. For instance, you'd make your PHP like this instead:

echo '<th><a href="?sort-by=email&order='. $this->order .'">E-Mail</a></th>';

(Simply removing the hash)

Then in JavaScript, we'd do this:

Element.href = Element.href + window.location.hash;

Where Element is the DOM selector method for the <a> tag.

EDIT Or if you have jQuery handy:

$("a").each(function(){
  $(this).attr("href", 
    $(this).attr("href") + window.location.hash
  )
});

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