如何编写一个变量以在多个页面上应用脚本?

时间:2019-01-15 17:36:57

标签: javascript jquery

我想在多个页面上应用相同的脚本,但是我需要在其中存储一些var,而在某些页面上可能不存在。

window.onorientationchange = function () {
var $t1 = $(".test1")[0];
var $t2 = $(".test2")[0];
var $t3 = $(".test3")[0];
var $t4 = $(".test4")[0];
var $t5 = $(".test5")[0];
// do some stuff
}

我想将此代码存储在.js文件中,然后将其应用于多个页面,问题是某些var在特定页面上不存在,如何使其通用?

如果我添加以下行:

if (window.matchMedia("(orientation: portrait)").matches) {        
  if ($t1.is(":empty") && $t2.is(":visible")) {}}

在提到的事件侦听器内部,如何处理上一步未定义的“空” var?

1 个答案:

答案 0 :(得分:0)

Several things.

Based on your variable naming, it looks like you are expecting $t1 to be a jQuery object.

However, when you try to access an element by index [0], you are returning the first element that matched the selector, no longer wrapped as a jQuery object.

What you want is to use the .eq(0) function to access the element by index, so a jQuery object is returned

https://api.jquery.com/eq/

var $t1 = $(".test1").eq(0);

At that point, you can use the .length test to check if your $t1 contains any elements

window.onorientationchange = function () {
    var $t1 = $(".test1").eq(0);
    // ...

    if($t1.length){
       // do stuff with $t1
    }
}