javascript jQuery - 如何测试链接是否锚定在同一页面上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33818702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - how to test if link goes to anchor on same page?
提问by Benek Lisefski
I'm trying to run an ajax function when links are clicked, but I need to exclude links to anchors on the same page so I don't try to re-load in the page content when I'm simply scrolling down to a different part of the same page.
我正在尝试在单击链接时运行 ajax 函数,但我需要排除指向同一页面上锚点的链接,因此当我只是向下滚动到不同的页面时,我不会尝试重新加载页面内容同一页面的一部分。
I know I can test if the href include a hash but that's not good enough:
我知道我可以测试 href 是否包含哈希值,但这还不够好:
if (href.indexOf("#") === -1)
Because I will have links that go to another page AND scroll to a local anchor. So I need to test if the href points to the current page AND includes a hash. And in that case I would exclude it from the function. But if it points to a different page and includes a hash it should still be included.
因为我将有链接到另一个页面并滚动到本地锚点。所以我需要测试 href 是否指向当前页面并包含哈希值。在那种情况下,我会将它从函数中排除。但是如果它指向一个不同的页面并包含一个散列,它仍然应该被包含在内。
How can I achieve this with jQuery?
我怎样才能用 jQuery 实现这一点?
回答by Molemann
This is my take, much slimmer :-
这是我的看法,更苗条:-
$('a[href*=\#]').on('click', function (event) {
if(this.pathname === window.location.pathname){
// Do something
}
});
回答by Rahul Desai
You do not need jQuery for this. Just use regex in Javascript.
为此,您不需要 jQuery。只需在 Javascript 中使用正则表达式。
if(/^#/.test(href)) { // .test() returns a boolean
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
Explanation:
解释:
^#
is the regex. //
is where you wrap your regex in. ^
means at the beginning of the string and #
is what you are looking for. .test()
is a javascript function that executes the regex on a given string and return a boolean value.
^#
是正则表达式。//
是您将正则表达式包裹起来的地方。^
意思是在字符串的开头,这#
就是您要查找的内容。.test()
是一个 javascript 函数,它在给定的字符串上执行正则表达式并返回一个布尔值。
Read up:RegExp.prototype.test()
- JavaScript | MDN
阅读:RegExp.prototype.test()
- JavaScript | MDN
Update 1:
更新 1:
In case if the href
is not starting with a #
but it still points to the same webpage, your problem is reduced to checking if a string is a substring of another string. You can make use of window.location.href
and .indexOf()
to achieve this:
如果href
不是以 a 开头#
但它仍然指向同一个网页,那么您的问题就简化为检查一个字符串是否是另一个字符串的子字符串。您可以利用window.location.href
并.indexOf()
实现这一点:
if(href.indexOf(window.location.href) > -1) {
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
window.location.href
returns the URL of the webpage that you are on and href.indexOf(window.location.href)
checks if window.location.href
is substring of href
;
window.location.href
返回您所在网页的 URL 并href.indexOf(window.location.href)
检查是否window.location.href
是 的子字符串href
;
Example: https://www.example.com/page1
is a substring of https://www.example.com/page1#myDiv
示例:https://www.example.com/page1
是一个子串https://www.example.com/page1#myDiv
Read up:
阅读:
Update 2:
更新 2:
Good find by @Tib. My code in update above was not checking if the hostnames are the same. I have fixed it below:
@Tib 的好发现。我上面更新中的代码没有检查主机名是否相同。我在下面修复了它:
if(<hostnames are the same>) { // make use of window.location.hostname here to get hostname of current webpage
if(href.indexOf(window.location.href) > -1) {
/* do not run AJAX function */
} else {
/* run the AJAX function */
}
} else {
/* do not run AJAX function */
}
回答by Rodrigo
Supported in all browsers:
支持所有浏览器:
"use strict"; // Start of use strict
$('a').bind('click', function(event) {
if (this.pathname == window.location.pathname &&
this.protocol == window.location.protocol &&
this.host == window.location.host) {
alert('links to same page');
event.preventDefault();
} else {
alert('links to a different page');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#same-page">Same Page</a>
<br>
<a href="/users/913950#page">Other Page</a>
回答by Jonathan Joosten
Far from perfect, but works for me. Don't forget to use jQuery.
远非完美,但对我有用。不要忘记使用jQuery。
Have fun with it:
玩得开心:
jQuery('a').on('click',function (e) {
var current = window.location.href.split('#')[0];
var goto = jQuery(this).attr('href').split('#')[0];
if (current == goto && this.hash) {
e.preventDefault();
var target = this.hash;
var $target = jQuery(target);
if($target.length){
jQuery('html,body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing');
}
}
});
jQuery('a[href^=#]:not([href=#])').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = jQuery(target);
if($target.length){
history.pushState( null, jQuery('#title').html() , target);
jQuery('html,body').stop().animate({
'scrollTop': $target.offset().top }, 900, 'swing');
}
});
jQuery('a[href=#]').on('click',function (e) {
e.preventDefault();
history.pushState( null, jQuery('#title').html() , location.href.replace(location.hash,""));
jQuery('html,body').stop().animate({
'scrollTop': 0
}, 900, 'swing');
});
回答by Alexey Kosov
/**
* Checks if the href belongs to the same page and returns the anchor if so.
*
* @param {String} href
* @returns {Boolean|String}
*/
function getSamePageAnchor (href) {
var link = document.createElement('a');
link.href = href;
/**
* For IE compatibility
* @see https://stackoverflow.com/a/24437713/1776901
*/
var linkCanonical = link.cloneNode(false);
if (
linkCanonical.protocol !== window.location.protocol ||
linkCanonical.host !== window.location.host ||
linkCanonical.pathname !== window.location.pathname ||
linkCanonical.search !== window.location.search
) {
return false;
}
return link.hash;
}