[英]How do I use JQuery inside a constructor function inside a JS namespace?
OK, yesterday I asked about this but there was a stupid bug in my code so I ended up getting the answer to the wrong question. 好的,昨天我问了这个问题,但是我的代码中有一个愚蠢的错误,所以我最终得到了错误问题的答案。
I want to use JQuery inside a javascript constructor function, which sits inside a namespace: 我想在位于名称空间内的javascript构造函数内使用JQuery:
var NS=NS||{};
NS.constructor=function()
{
this.problem="doing my head in"
this.solution="looking very messy"
function useJQuery()
{
$(document).ready
(
function()
{
$('body').html("I've written out the whole 'document ready function thing");
}
)
}
function usePlainJS()
{
return "Now I'm using plain JS";
}
function useJQueryAgain()
{
$(document).ready
(
function()
{
$('body').html("Now I've written out the 'document ready' thing AGAIN!");
}
)
}
} }
Is there a better way of doing this, without writing out the whole 'document ready' thing every time I want to use JQuery? 有没有一种更好的方法,而不必每次我想使用JQuery都写出整个“文档就绪”的东西?
Approach one. 方法一。 You can avoid repetitive
$(document).ready
blocks if you wrap function invocations themselves into $(functionName)
. 如果将函数调用自身包装到
$(functionName)
则可以避免重复的$(document).ready
块。 For example: 例如:
var NS = NS || {};
NS.constructor = function() {
this.problem = "doing my head in"
this.solution = "looking very messy"
// Here is an example of usage this function
$(useJQuery);
function useJQuery() {
$('body').html("I've written out the whole 'document ready function thing");
}
function usePlainJS() {
return "Now I'm using plain JS";
}
function useJQueryAgain() {
$('body').html("Now I've written out the 'document ready' thing AGAIN!");
}
};
Approach two. 方法二。 Put all your code before closing
</body>
tag, after the rest of the DOM contents. 将所有代码放在
</body>
标记之前,其余DOM内容之后。 This way you don't have to worry about document ready, because by the moment script is executed HTML structure is already available. 这样,您不必担心文档是否准备就绪,因为在执行脚本时,HTML结构已经可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.