سؤال

My problem is to execute a function when a new page is loaded. I have two pages (index.html and location_page.html). In the first one there is a list of labels. When the user click on one element of this list, he is redirected to the second page that should dynamically load the info associated. I tried to use function ready but it doen't work. Here is my jQuery code

$("#location_title").ready(function(e){
    console.log("executing the function");
});

and here is the HTML

<div class="location_info">
    <div class="location_text">
    <div id="location_title"></div>
        <div id="location_description"></div>
    </div>
    <div class="location_img"><img src="./img/strutture01.jpg" class="location_image"/></div>           
     </div>  

The first page also has a method like this (i call a 'ready' function) and it works, but it doesn't works on the second page.

هل كانت مفيدة؟

المحلول

Pass a query string saying location_page.html?info=1

Use this function to get the query string value,

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

So on document ready, call the function

$(document).ready(function(){  
    value = getParameterByName("info");
    if (value == '1')
    {
        $("#location_title").show();
        // Do your stuff
    }
    console.log("executing the function");  
});

getParameterByName() function is taken from Get query string values in JavaScript

UPDATE:

Replace this

$("#location_title").ready(function(e){   

with

$(document).ready(function(){

نصائح أخرى

try using HTML onLoad attribute in HTML <body> tag and from that call your function in the Javascript..

i.e. i Javascript;

function doSomeThing(){ /*your code*/ }

and in HTML;

<body onload='doSomething()'>
   <!-- your html body -->
</body>

Hope it helps :-)

For that you'll want a simple self-executing anonymous:

(function() {
    $("#location_title").ready(function(e){
        console.log("executing the function");
    });
})();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top