Using PHP or JavaScript, can I append some text to every href URL rendered in a page?

╄→гoц情女王★ 提交于 2019-12-13 07:21:23

问题


first time posting! I'll try to be as clear as possible.

I have a Drupal 6 website and am using a custom template file to render some pages differently than the rest of the website.

This is what the code I'm working with looks like:

<?php print $header; ?> 
<?php if ($title): ?><h1><?php print $title; ?></h1><?php endif; ?>
<?php print $content ?>

The page renders correctly when the URL looks like this: http://example.com/somepage/?format=kiosk

Except any link that is rendered in the page will go to: http://example.com/otherpage/

What I need dynamically appended to the end of any URL is:

?format=kiosk

Is there a to process these links using PHP or JavaScript, without resorting to .htaccess (though that's an option), to add that bit to the URL?

I suppose this could also be handy for other things, like Google Analytics.

Thanks!

Jon


回答1:


Here is a solution using jQuery which runs a quick regex check to make sure the anchor tag is a link to a page on http://example.com. It also checks to see if the link already has a ? or not.

var $links = $('a'); // get all anchor tags

// loop through each anchor tag
$.each($links, function(index, item){
    var url = $(this).attr('href'); // var for value of href attribute
    // check if url is undefined
    if(typeof url != 'undefined') {
        // make sure url does not already have a ?
        if(url.indexOf('?') < 0) {
            // use regex to match your domain
            var pattern = new RegExp(/(example.com\/)(.*)/i);
            if(pattern.test(url))
                $(this).attr('href', url + '?format=kiosk'); // append ?format=kiosk if url contains your domain
        }
    }
});



回答2:


Sure, just gather all elements with a href attribute and tack it on from there.

var links = document.querySelectorAll('[href]');
for (var i = 0; i < links.length; i++) {
  links[i].href += '?format=kiosk';
}

You'll probably want to do a simple check first to see if the link contains a ? (links[i].href.indexOf('?') > -1) but this will make sure that every href ends in ?format=kiosk.




回答3:


window.history.pushState(window.location.href, "Title", "?format=kiosk");

This will get the current url and append a string you specify at the end



来源:https://stackoverflow.com/questions/31860361/using-php-or-javascript-can-i-append-some-text-to-every-href-url-rendered-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!