简体   繁体   中英

Change text based on parameter within link - ex. welcome message with name

I have a problem with creating simple script. I'm trying to trigger text change when user click specially prepared link.

I'm sending to my friends via email or messenger link to website with our tournaments. On this website I want to welcome them by custom message. But each of them have separate link like:

www.mywebsite.com/#john1
www.mywebsite.com/#john2

So when ex. one of them access website via link:

www.mywebsite.com/#john1

I want to display custom message for him. Custom title. But when other friends access website via link:

www.mywebsite.com

Everything will be default. No change is needed to this title.

Is there any easy way to achieve this?

I tried to achieve something like onclick event with jquery. Set there text for all of this and than access them via mywebsite.com/#john1 etc But looks like this is a bad idea because this doesn't work when add parameter to link. Only when click element on website.

I tried something like this:

$(function() {
    $("#john1, #john2").on("click", function(e) {
        var txt = "";
        switch ($(this).prop("id")) {
            case "john1":
                txt = "Hi john 1";
                break;
            case "john2":
                txt = "Hi John 2";
                break;
        }
        $("#h1-title").text(txt);
    })
})

and than access like: www.mywebsite.com/#john2

But I know this isn't good use case for that.

So basically what you are trying to do is to have a customized greeting message for every visitor you send him a customized URL, but show no message for the ordinary URL.

This can be done as follows:

  1. Define the format of the customized URL. www.mywebsite.com#john1 looks so fine. (Note that there is not slash before the hash! It's not a sub-directory.
  2. Have a function that determines the name of the visitor:
function getVisitorName(){
    let name = window.location.href;
    let indexOfHash = name.indexOf('#');
    if(indexOfHash === -1){return null;}
    name = name.slice(indexOfHash+1, name.length)
    return name;
  }
  1. Now, call this function upon the event you like. (Page load for example):
$(document).ready(()=>{
    let name = getVisitorName;
    if (name === null) {return;}
    let message = "Hi " + name + " !";
    $("#h1-title").text(message);
  })
  1. Send links to your friends customized as www.mywebsite.com#John1 , www.mywebsite.com#John2 ..etc.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM