我可以使用PHP或JavaScript将一些文本附加到页面中呈现的每个href URL吗? [英] Using PHP or JavaScript, can I append some text to every href URL rendered in a page?
问题描述
首次发布!我会尽量保持清晰。
first time posting! I'll try to be as clear as possible.
我有一个Drupal 6网站,并且正在使用自定义模板文件来呈现某些页面,而不是网站的其余部分。 。
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 ?>
URL如下所示,页面可以正确显示: http://example.com/somepage/?format=kiosk
The page renders correctly when the URL looks like this: http://example.com/somepage/?format=kiosk
页面中呈现的任何链接都将转到: http://example.com/otherpage/
Except any link that is rendered in the page will go to: http://example.com/otherpage/
我需要动态附加到任何URL末尾的内容是:
What I need dynamically appended to the end of any URL is:
?format=kiosk
是否可以使用PHP或JavaScript处理这些链接,而无需使用.htaccess (尽管这是一个选择),要将其添加到URL中?
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?
我想这对于其他事物(例如Google Analytics(分析))也很方便。
I suppose this could also be handy for other things, like Google Analytics.
谢谢!
Jon
推荐答案
以下是使用jQuery的解决方案,该解决方案运行快速的正则表达式检查以确保锚标记是指向 http://example.com 。它还检查链接是否已经有一个?
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
}
}
});
这篇关于我可以使用PHP或JavaScript将一些文本附加到页面中呈现的每个href URL吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!