Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

javascript - Best way to execute js only on specific page

I was wondering what would be the best way to execute a java-script code only on specific pages.

Let's imagine we have a template-based web-site, rewrite rule for the content ist set, jquery available and it basically looks like this:

  <!DOCTYPE html>
  <html>
   <head>
    <script src="script.js"></script>
   </head>
   <body>
    ...
    include $content;
    ..
   </body>
</html>

content 'info' contains a button, we want something to happen on click, content 'alert' should give us a message when you hover a text field.

What is the best way to trigger these actions, without running into an error, because the object is not found?

Option one: using window.location.pathname

 $(document).ready(function() {
      if (window.location.pathname == '/info.php') {
          $("#button1").click(function(){
            //do something
          })
      }else if(window.location.pathname == '/alert.php'){
           $("#mytextfield").hover(){
             alert('message');
           }
    }

Option two: checking if elements exist

$(document).ready(function() {
  if ($("#button1").length > 0) {
      $("#button1").click(function(){
        //do something
      })
  }else if ($("#mytextfield").length > 0){
       $("#mytextfield").hover(){
         alert('message');
       }
}

Option three: include the script in the loaded template

//stands for itself

Is there a better solution? Or do I have to get along with one of these solutions?

Your experience, usage, or any links related to this topic are appreciated.

//EDIT:

I might have choosen a bad example, the actual code would be somethin like:

    mCanvas = $("#jsonCanvas");
    mMyPicture = new myPicture (mCanvas);

where the myPicture constructor get's the context of the canvas element, and throws an error, if mCanvas is undefined.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set a class attribute to your body tag.

<body class="PageType">

And then in your script..

$(function(){
  if($('body').is('.PageType')){
    //add dynamic script tag  using createElement()
    OR
    //call specific functions
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...