仅在特定页面上执行js的最佳方法

Joh*_*lin 51 html javascript performance jquery

我想知道在特定页面上执行java脚本代码的最佳方法是什么.

让我们假设我们有一个基于模板的网站,内容集的重写规则,jquery可用,它基本上是这样的:

  <!DOCTYPE html>
  <html>
   <head>
    <script src="script.js"></script>
   </head>
   <body>
    ...
    include $content;
    ..
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

内容'info'包含一个按钮,我们希望在点击时发生某些事情,当您悬停文本字段时,内容'alert'应该作为消息提供.

触发这些操作的最佳方法是什么,而不会遇到错误,因为找不到该对象?

选项一:使用 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');
           }
    }
Run Code Online (Sandbox Code Playgroud)

选项二:检查元素是否存在

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

选项三:在加载的模板中包含脚本

//stands for itself
Run Code Online (Sandbox Code Playgroud)

他们是更好的解决方案吗?或者我必须与这些解决方案中的一个相处?

我们非常感谢您的体验,用法或与此主题相关的任何链接.

//编辑:

我可能选择了一个不好的例子,实际的代码可能是:

    mCanvas = $("#jsonCanvas");
    mMyPicture = new myPicture (mCanvas);
Run Code Online (Sandbox Code Playgroud)

如果mCanvas未定义,则myPicture构造函数获取canvas元素的上下文,并抛出错误.

Rob*_*ben 67

class属性设置为body标签.

<body class="PageType">
Run Code Online (Sandbox Code Playgroud)

然后在你的脚本中..

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

  • 很好的答案,但`hasClass()`比`is()`表现更好.如果您正在运行多个条件来确定您所使用的页面中存在的页面,我建议您切换正在使用的功能. (7认同)
  • 或者,可以使用"data"属性.我更喜欢将`data-*`用于将在JS中使用的选择器,这样我知道该元素以某种方式与JS交互.在body中添加一个`data-page`属性,然后检查`document.body.getAttribute('data-page')=='pagetype'`.准备好运行它. (5认同)
  • 我认为将类名添加到每个页面是一种好习惯。.js和css (2认同)

Ohg*_*why 15

我会使用switch语句和变量.(我正在使用jQuery!)

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname

switch(windowLoc){      
  case "/info.php":
    //code here
    break;
  case "/alert.php":
    //code here
    break;
}

//use windowLoc as necessary elsewhere
Run Code Online (Sandbox Code Playgroud)

这将允许您根据您所在的页面更改"按钮"的功能.如果我理解你的问题; 这就是我要做的.另外,如果我提供了大量的javascript,我只需完全添加一个新的JS文件.

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname

switch(windowLoc){      
  case "/info.php":
    var infoJS = document.createElement('script');
    infoJS.type = 'text/javascript';
    infoJS.src = 'location/to/my/info_file.js';
    $('body').append(infoJs);
    break;
  case "/alert.php":
    var alertJS = document.createElement('script');
    alertJS.type = 'text/javascript';
    alertJS.src = 'location/to/my/alert_file.js';
    $('body').append(alertJs);
    break;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 -

干杯.


Nik*_*hil 10

与检查URL路径有点不同的方法:您可以在单个函数中对页面特定的事件处理程序进行分组,然后在每个包含中,有一个domready将调用这些函数.

例如:script.js你有两个功能(在domready之外)即.onPage1Load()onPage2Load().

在你的同时page1.php你有$(document).ready(onPage1Load) 其他页面等等.这将确保未注册非预期的事件处理程序.