Monday 12 June 2017

javascript - Passing variable to function on another page




I am working on a website and am planning on having it so that certain links will have a value set, this will change what container is displayed when the page loads. How would I have it so the link passes a value that would be used for the onload functions?



Here is a mockup of my HTML code:







Lunch













The recipes you'll find here are ones you can use to impress guests at your next get together






Chicken Clubhouse Sandwiches




Smokey Tomato Soup










And here is my tabulate function:



function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}

else{
this.style.display="none";
}
});

}

Answer



You would need to make use of the URL's GET parameters:




lunch.html?item=2


In conjunction with passing the variable into the JavaScript function:



// Set up an object for GET parameter
var $_GET = {};

// Find and extract the various GET parameters
if(document.location.toString().indexOf('?') !== -1) {

var query = document.location.toString().replace(/^.*?\?/, '').replace(/#.*$/, '').split('&');
for(var i=0, l=query.length; i var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}

// Target a specific get parameter, given the GET parameter name
var tabNum = $_GET['item']; // Comes through as '2' in this example


// Pass the parameter into the function
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});

}


See this post and this post for further reference.



Hope this helps! :)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...