How to set up javascript/jquery code for whole site or one page or some of both?
Can someone explain this to me. I have 1 js file on my site, using mainly jQuery, all my js code uses elements that are on all pages, EXCEPT for 1 js code that targets an element that is only on one page.
So when I go to that one page, I get no JavaScript errors, however when I go to any other page it gives me a $..Undefined
error for that element. I am using a .offset().top
code for that element. I'm assuming that's because if you only target an element that's on one page I should just include a script on that page alone and not put it in my js file??? Does that include all jquery functions or just something specific to using .offset()
and/or others? Is my assumption correct?
Just put a quick check for that element in your JS file. Example, the element only on one page:
<span id="coolSpan">span stuff</span>
JS:
if ($("#coolSpan").length) {
//element exists, bind the handler
$("#coolSpan").click(function() {
console.log("I exist!");
});
}
What I like to do is write my js pages like so:
var initMyFunction = function(){
*code for initMyFunction*
};
var initMyOtherFunction = function(){
*code for initMyOtherFunction*
};
And then in my mark up I can call which function I want to run on that page, so long as I call it after I call my script.
<!-- Scripts -->
<script src="js/main.js"></script>
<!-- Inits -->
<script>initMyFunction();</script>
It has the benefit of only running the code you need ran on that page, instead of running all your js on every page.
If you are trying to access a function of an element that is not there, you will get an error regardless of the function you are using.
Solutions:
Like you said, you can put the specific code in a separate .js file and include that file only in the appropriate HTML page.
You could check for the element's existence and only then proceed with manipulating it. Eg:
var elem = document.getElementById("mySpecialElement"); if (elem) { /* Element exists, it is safe to manipulate it */ $(elem).offset()... }链接地址: http://www.djcxy.com/p/83708.html
上一篇: 按属性选择元素