كيف يمكنك التحقق من وجود #hash في عنوان URL باستخدام JavaScript؟
-
08-07-2019 - |
سؤال
لدي بعض أكواد jQuery/JavaScript التي أريد تشغيلها فقط عندما يكون هناك تجزئة (#
) رابط الربط في عنوان URL.كيف يمكنك التحقق من هذه الشخصية باستخدام جافا سكريبت؟أحتاج إلى اختبار شامل بسيط يمكنه اكتشاف عناوين URL مثل هذه:
example.com/page.html#anchor
example.com/page.html#anotheranchor
في الأساس شيء على غرار:
if (thereIsAHashInTheUrl) {
do this;
} else {
do this;
}
إذا كان بإمكان أي شخص أن يوجهني في الاتجاه الصحيح، فسيكون ذلك موضع تقدير كبير.
المحلول
بسيط:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
نصائح أخرى
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
alert (hash);
// hash found
} else {
// No hash found
}
ضع ما يلي:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
// Your code in here accessing the string like this
// location.href.substr(location.href.indexOf("#"))
}
</script>
إذا لم يكن URI هو موقع المستند، فسيقوم هذا المقتطف بما تريد.
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
هل جربت هذا؟
if (url.indexOf("#") != -1)
{
}
(أين url
هو عنوان URL الذي تريد التحقق منه بوضوح.)
$('#myanchor').click(function(){
window.location.hash = "myanchor"; //set hash
return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
//do sth here, hell yeah!
});
هذا سوف يحل المشكلة ؛)
window.location.hash
سيعود معرف التجزئة
...أو هناك محدد مسج:
$('a[href^="#"]')
إليك ما يمكنك فعله للتحقق بشكل دوري من تغيير التجزئة، ثم استدعاء وظيفة لمعالجة قيمة التجزئة.
var hash = false;
checkHash();
function checkHash(){
if(window.location.hash != hash) {
hash = window.location.hash;
processHash(hash);
} t=setTimeout("checkHash()",400);
}
function processHash(hash){
alert(hash);
}
يعرف معظم الأشخاص خصائص عنوان URL في document.location.يعد هذا أمرًا رائعًا إذا كنت مهتمًا بالصفحة الحالية فقط.لكن السؤال كان حول القدرة على تحليل نقاط الارتساء على الصفحة وليس الصفحة نفسها.
يبدو أن ما يفتقده معظم الأشخاص هو أن خصائص عنوان URL نفسها متاحة أيضًا لعناصر الربط:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
function getHash() {
if (window.location.hash) {
var hash = window.location.hash.substring(1);
if (hash.length === 0) {
return false;
} else {
return hash;
}
} else {
return false;
}
}
تعليقات بارتريدج وجاريث أعلاه رائعة.إنهم يستحقون إجابة منفصلة.من الواضح أن خصائص التجزئة والبحث متاحة على أي كائن رابط html:
<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
alert(document.getElementById('test').search); //bar
alert(document.getElementById('test').hash); //quz
</script>
أو
<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
إذا كنت بحاجة إلى ذلك على متغير سلسلة منتظم وتصادف أن يكون لديك jQuery ، يجب أن يعمل هذا:
var mylink = "foo.html?bar#quz";
if ($('<a href="'+mylink+'">').get(0).search=='bar')) {
// do stuff
}
(ولكن ربما يكون مبالغا فيه بعض الشيء ..)
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
طرح هذا هنا كطريقة لاستخراج خصائص الموقع من سلاسل عشوائية تشبه URI.بالرغم من window.location instanceof Location
صحيح، أي محاولة للاستدعاء Location
سيخبرك أنه منشئ غير قانوني.لا يزال بإمكانك الوصول إلى أشياء مثل hash
, query
, protocol
إلخ عن طريق تعيين السلسلة الخاصة بك كـ href
خاصية عنصر ربط DOM، والتي ستشارك بعد ذلك جميع خصائص العنوان معها window.location
.
أبسط طريقة للقيام بذلك هي:
var a = document.createElement('a');
a.href = string;
string.hash;
للراحة، كتبت مكتبة صغيرة تستخدم هذا لتحل محل اللغة الأصلية Location
منشئ مع واحد من شأنه أن يأخذ سلاسل وينتج window.location
-الكائنات المشابهة: Location.js
عادة ما تنقر أولاً من تغييرات الموقع ، لذلك بعد النقر تكون فكرة جيدة لـ SetTimeOut للحصول على نافذة محدثة. location.hash
$(".nav").click(function(){
setTimeout(function(){
updatedHash = location.hash
},100);
});
أو يمكنك الاستماع إلى الموقع مع:
window.onhashchange = function(evt){
updatedHash = "#" + evt.newURL.split("#")[1]
};
كتبت أ البرنامج المساعد مسج هذا يفعل شيئًا مثل ما تريد القيام به.
إنه جهاز توجيه مرساة بسيط.
هنا وظيفة بسيطة ترجع true
أو false
(لديه/ليس لديه علامة تصنيف):
var urlToCheck = 'http://www.domain.com/#hashtag';
function hasHashtag(url) {
return (url.indexOf("#") != -1) ? true : false;
}
// Condition
if(hasHashtag(urlToCheck)) {
// Do something if has
}
else {
// Do something if doesn't
}
عائدات true
في هذه الحالة.
بناءً على تعليق @jon-skeet.
هذه طريقة بسيطة لاختبار ذلك لعنوان URL للصفحة الحالية:
function checkHash(){
return (location.hash ? true : false);
}
في بعض الأحيان تحصل على سلسلة الاستعلام الكاملة مثل "#anchorlink?firstname=mark"
هذا هو البرنامج النصي الخاص بي للحصول على قيمة التجزئة:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink