1

我正在尝试从 window.location 提取哈希子字符串值并将它们写入 HTML 以供用户查看,其 URL 语法不允许?用作查询字符串分隔符。

所以我正在使用这个简单的页面:

<html>

<input type="button" id="test" value="Test" />
<!-- input buton is here just to test the script -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<script>
$(function() {
    $('#test').click(function() {
        window.location = (window.location);
        GetURLParameter('source');  
    });
});

function GetURLParameter(sParam) {
    var sPageURL = window.location.hash.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            alert(sParameterName[1]);
            return sParameterName[1];
        }
    }
} 
</script>

</html>

我使用如下所示的 URL 调用页面,即客户端 window.location:

http://example.com/pagename.html#source=FOO&medium=BAR&campaign=FRED

我想在页面中写入 FOO、BAR、FRED,以便用户可以看到。

(注意?在 URL 中没有作为查询字符串分隔符,只是#

...单击输入按钮时,我收到一个成功的警报(如预期的那样),显示来自 URL 的源“FOO”。伟大的。

But how do I get the other two SParamaterNames, and then how do I write them into the page as HTML for the user to see, rather than return an alert?


UPDATE UPDATE UPDATE (below)

Thanks, @sam-baker!! ... Great answer. I used your first example, but changed the first two lines in your code to $(window).load(function() { so that the script runs onload, which was my intent.

So, I am still using this same URL:

http://example.com/pagename.html#source=FOO&medium=BAR&campaign=FRED

But I want to insert the hash substring values into hardcoded HTML, like this:

<body>
<span class="style1">$need_source_value_here</span><br />
<span class="style1">$need_medium_value_here</span><br />
<span class="style3">$need_campaign_value_here</span><br />

I will style each value individually, by hardcoding span or div styles into the HTML.


UPDATE UPDATE UPDATE

Here's the solution:

Hit the following simple page in the code example bellow with this URL syntax, and it will output the substring vars to the user, onload, wherever you want them on the page.

http://example.com/pagename.html#dyntext=FOO+MAN+CHU&dynterm=BAR+HOPPING&dynimage=FRED+IS+DEAD



<html>
<body>

<span id="dyntext-span" style="font-weight: bold;"></span><br />
<span id="dynterm-span" style="font-style: italic;"></span><br />
<span id="dynimage-span" style="text-decoration: underline;"></span><br />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<script>
$(document).ready(function() {
        var tags = ["dyntext", "dynterm", "dynimage"];
        for (var i = 0; i < tags.length; ++i) {
            var param = GetURLParameter(tags[i]);
            if (param) {
                var dyntext = GetURLParameter('dyntext');
                var dynterm = GetURLParameter('dynterm');
                var dynimage = GetURLParameter('dynimage');
            }
        }

        var elem = document.getElementById("dyntext-span");
        var text = document.createTextNode(dyntext);
        elem.appendChild(text);
        var elem = document.getElementById("dynterm-span");
        var text = document.createTextNode(dynterm);
        elem.appendChild(text);
        var elem = document.getElementById("dynimage-span");
        var text = document.createTextNode(dynimage);
        elem.appendChild(text);     
});

function GetURLParameter(sParam) {
    var sPageURL = window.location.hash.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}

</script>

</body>
</html>

Had some crossbroswer issues because innerText is not supported by Firefox, did not want to deal with cross-browser fallback to textContent, etc, so just walked DOM tree and created text nodes, replacing the + unicode character with space. Hope this is useful to you!

4

1 回答 1

1

You're only requesting the first of the 3 parameters using:

GetURLParameter('source');

If you want all 3 parameters and you know the names, you can use:

var source = GetURLParameter('source');
var medium = GetURLParameter('medium');
var campaign = GetURLParameter('campaign');

To add those vars to the page, you can insert them in divs like this:

<input type="button" id="test" value="Test" />
<!-- input buton is here just to test the script -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<script>
$(function() {
    $('#test').click(function() {
        // Iterate through a known list of tags
        var tags = ["source", "medium", "campaign"];
        for (var i = 0; i < tags.length; ++i) {
            var param = GetURLParameter(tags[i]);
            if (param) {
                var div = document.createElement('div');
                div.innerText = param;
                div.className = "query-string-param";
                document.body.appendChild(div);
            }
        }
    });
});

function GetURLParameter(sParam) {
    var sPageURL = window.location.hash.substring(1);

    console.log(sPageURL);

    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
} 
</script>

</html>

That version queries each of the 3 tags and creates a new div in the page for that tag with the tag's value as the content.

It also adds a CSS class, query-string-param to those divs so that you can style the text - presumably you'll want to do that, and add more HTML to each div since it's not clear why that text is displayed.

If you don't know the query string keys upfront (source, medium and campaign), you could use a function I created, GetAllURLParameters that returns an array of objects with both the key ("source") and the value ("FOO") for each param.

That would look like this:

<input type="button" id="test" value="Test" />
<!-- input buton is here just to test the script -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

<script>
$(function() {
    $('#test').click(function() {
        // Iterate through a known list of tags
        var params = GetAllURLParameters();
        for (var i = 0; i < params.length; ++i) {
            var param = params[i];
            var div = document.createElement('div');
            div.innerText = "Value of param '" + param.key + "' is '" + param.value + "'";
            div.className = "query-string-param";
            document.body.appendChild(div);
        }
    });
});

function GetURLParameter(sParam) {
    var sPageURL = window.location.hash.substring(1);

    console.log(sPageURL);

    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
} 

function GetAllURLParameters() {
    var sPageURL = window.location.hash.substring(1);
    var params = [];
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        params.push({
            key: sParameterName[0],
            value: sParameterName[1]
        });
    }
    return params;
}
</script>

</html>

Which then shows the names and values of all query parameters.

UPDATE

Since you already have hardcoded HTML that looks like this:

<span class="style1">$need_source_value_here</span><br />
<span class="style1">$need_medium_value_here</span><br />
<span class="style3">$need_campaign_value_here</span><br />

The easiest way to insert your values would be to add an id to each of those spans:

<span id="source-span" class="style1"></span><br />
<span id="medium-span" class="style1"></span><br />
<span id="campaign-span" class="style3"></span><br />

Then after you query the parameters, you can insert them like this:

var source = GetURLParameter('source');
document.getElementById('source-span').innerText = source;
var medium = GetURLParameter('medium');
document.getElementById('medium-span').innerText = medium;
var campaign = GetURLParameter('campaign');
document.getElementById('campaign-span').innerText = campaign;
于 2012-08-30T22:26:24.707 回答