Szukam sposobu wyszukiwania adresu URL strony, szukając konkretnego słowa kluczowego w ma.
Na przykład, jeśli istnieje Hash "/ Three", chcę uruchomić funkcję JavaScript. Problem polega jednak na tym, że mam osiem skrótów i mogą być wywołane w każdej konkretnej kolejności.
Oznacza to, że nie mogę po prostu zrobić coś takiego -
<script>
window.onhashchange = function(){
switch(location.hash) {
case '#hide':
javascript:alert("Find a valid NFC tag to continue!")
break;
case '#hide/one':
javascript:alert("You found piece number one!")
break;
case '#hide/two':
javascript:alert("You found piece number two!")
break;
case '#hide/three':
javascript:alert("You found piece number three!")
break;
case '#hide/four':
javascript:alert("You found piece number four!")
break;
case '#hide/five':
javascript:alert("You found piece number five!")
break;
case '#hide/six':
javascript:alert("You found piece number six!")
break;
case '#hide/seven':
javascript:alert("You found piece number seven")
break;
case '#hide/eight':
javascript:alert("You found piece number eight!")
break;
}
}
</script>
Ponieważ adres URL może być "przykładem.com/index.html#hide/one/five/three/etc ..". Sposób, w jaki jest teraz skonfigurowany, jest to, że jest to szczególne wyszukiwanie "# Hide / One", "# Ukryj / dwie" itp.
Ale "#hide" nie jest włożony z każdym hash, tylko z pierwszym. Więc nigdy nie będzie "# Hide / One / # Hide / Two, Ett".
Muszę dowiedzieć się, jak mogę szukać "One", "dwa", "trzy" itp., W URL odpowiednio funkcje.
Z góry dziękujemy, czekamy na więcej na tym!
Edytuj - Wystarczy przeczytać mój post i czuję, że powinienem coś wyjaśnić. Znasz funkcję JavaScript "Hash.length"? Coś w rodzaju "hash.length", ale dla treści, jak "hash.content" lub coś byłoby świetnie. Nie sądzę, że istnieje.
-Mitchyl.
3 odpowiedzi
var hashArray = location.hash.substr(1).split('/'); // substr(1) skips over the # at the beginning
if (hashArray.indexOf('hide') != -1) {
if (hashArray.indexOf('one') != -1) {
alert("You found piece number one");
} else if (hashArray.indexOf('two') != -1) {
alert("You found piece number two");
} ...
}
BTW, nie potrzebujesz etykiety javascript:
przed połączeniami do alert()
. Jedyny czas potrzebny javascript:
jest wtedy, gdy wprowadzasz skrypt w atrybucie HTML, który zwykle zawiera adres URL, np. href
i atrybuty src
- zajmuje miejsce czegoś takiego jak http:
, aby powiedzieć, aby uruchomić kod, a nie pobrać dokument.
Działa w tym Demo. Po kliknięciu linku, edytuj adres URL i zmień one
do two
, otrzymasz alert.
Ten jest bardziej dynamiczny.
Musisz tylko zmienić pierwszy var "ahash", a reszta będzie autobiuld. BTW jest to tylko Nesecary, aby zapobiec reakcji skryptów na manipulacji Hash przez sam użytkownika. W przeciwnym razie możesz po prostu iterować sznurka splitowego Hash, ale byłoby to błędne.
// here goes the configuration
// if you want to change the "keys" here's the right place
// therefor it's better maintainable
var aHash = ['one', 'two', 'three'];
// autobuild an object with values as keys from given array at the top
var oHash = {},
i = aHash.length;
// don't forget that iteration usually starts with [0] but if you get the length will be 1 if one element is available
while( i-- )
{
oHash[ aHash[ i ] ] = null;
}
window.onhashchange = function()
{
// split hash into pieces into an array
aHash = document.location.hash.split('/');
var iL = aHash.length;
// workaround for case: '#hide/'
if (aHash[ iL-1 ] === '')
{
--iL;
}
if (iL == 1 && aHash[0] === '#hide')
{
alert ('Find a valid NFC tag to continue!');
return;
}
// only needed if one wants to collect the result
var sAlert = '';
// iterate from left to right in hash
// if this isn't nessecary one can use the same while structure like at the beginning (without iL)
i = -1;
while( ++i < iL )
{
if (oHash[ aHash[ i ] ] === null )
{
// alert every time
alert( 'You found piece number ' + aHash[ i ] + '!' );
// colect for alert
sAlert += aHash[ i ] + ' and ';
}
}
if (sAlert !== '')
{
alert( 'You found pieces number ' + sAlert.substr( 0, sAlert.length-5 ) + '!' );
}
}
Jeśli chcesz przetestować, że Hash zaczyna się od #hash
i liczby istnieją na ścieżce Hash, możesz spróbować tego.
window.onhashchange = function() {
if (location.hash.indexOf('#hash') !== 0) {
return;
}
location.split('/').forEach(function(num) {
switch (num) {
case 'one':
alert("You found piece number one!");
break;
// ...
case 'eight':
alert("You found piece number eight!");
break;
}
});
}
Należy pamiętać, że ta nie będzie działać w IE7 lub IE8.