我怎样才能让 jQuery 在 Wordpress 的新标签页中只打开 post 这段代码的链接
How can I make jQuery open only post links in new tabs in Wordpress for this code
我的 header.php 中有此代码:
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("a").click(function(){
jQuery("a").attr("target","_blank");
url=jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
</script>
现在它会在新的浏览器选项卡中打开所有链接。我想要的是只打开 posts。永久链接看起来像我的网站。com/this-is-the post/ 如果这有任何帮助的话。
请帮忙
谢谢
您可以使用 jQuery 的 .filter()
方法过滤链接。只需自定义正则表达式以满足您的实际需求
jQuery(document).ready(function() {
jQuery("a")
.filter(function() {
var href = jQuery(this).attr('href');
// return true if href exists and matches the regular expression
return href && href.match(/mywebsite\.com\/[\w-]+/);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
更新
如果你想要相反的行为,你可以使用.not()
jQuery(document).ready(function() {
jQuery("a")
.not(function() {
var href = jQuery(this).attr('href') || '';
// return true if href exists and matches the regular expression
return href.match(/mywebsite\.com\/[\w-]+/);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
我的 header.php 中有此代码:
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("a").click(function(){
jQuery("a").attr("target","_blank");
url=jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
</script>
现在它会在新的浏览器选项卡中打开所有链接。我想要的是只打开 posts。永久链接看起来像我的网站。com/this-is-the post/ 如果这有任何帮助的话。
请帮忙
谢谢
您可以使用 jQuery 的 .filter()
方法过滤链接。只需自定义正则表达式以满足您的实际需求
jQuery(document).ready(function() {
jQuery("a")
.filter(function() {
var href = jQuery(this).attr('href');
// return true if href exists and matches the regular expression
return href && href.match(/mywebsite\.com\/[\w-]+/);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
更新
如果你想要相反的行为,你可以使用.not()
jQuery(document).ready(function() {
jQuery("a")
.not(function() {
var href = jQuery(this).attr('href') || '';
// return true if href exists and matches the regular expression
return href.match(/mywebsite\.com\/[\w-]+/);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});