开发者

How to make my function to be page specific or div id specific?

I am writing javascrip开发者_运维百科t to my web pages, but there is a number of functions and loops, that i think are running in all pages, so the first one is running and failing on the second page. Because of this, the javascript function on the second page is not running.

Can anyone give me an idea of how to create page-specific functions or check the availability of an id? I don't use any frameworks.

thanks in advance.

my javascript code is :

window.onload = function(){  
   var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');  
   var signUp = document.getElementById('signup-link');      
    function animeYellowBar(num){  
      setTimeout(function(){  
          yellows[num].style.left = "0";  

          if(num == yellows.length-1){  
              setTimeout(function(){  
                  signUp.style.webkitTransform = "scale(1)";  
              },num * 250);  
          }  
      }, num * 500);  
    }
    for (var i = 0; i < yellows.length; i++){  
      animeYellowBar(i);  
    }

    alert("alert second page");  
}

in this code, the alert message not working on second page. any idea?


If I understand you correctly, you have a javascript function, that you want to attach to an event from a specific div element in your page.

a) Include an event directly to you HTML page, something like this:

<div id="element" onclick="some_function();">Text is here</div>

b) Use a javascript function (add this code between <script> tag):

window.onload = function() {
   document.getElementById("element").setAttribute("onclick", "some_function()")
}


The best way would be to only include those scripts on the pages which need them. Why waste time loading and parsing scripts you don't need?

If you must keep them on every page, put your functions in an if statement and check for something unique to the page that needs them (such as a form element or field ID).

Update

In response to your comment:

You have to code more defensively. You are attempting to make use of the magazine-brief and signup-link elements before you have made certain that they exist. Never trust that the proper element was returned - always check that it was before attempting to use that element.

I suggest checking your vars like so:

var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');

if (yellows != 'undefined' && signUp != undefined)
{
    function animeYellowBar(num)
    {
       //...
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜