好的,昨天我问了这个,但我的代码中有一个愚蠢的错误,所以我最终得到了错误问题的答案。
我想在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!");
}
)
}
}
有没有更好的方法来做到这一点,而不是每次我想使用JQuery时都写出整个'文档就绪'的东西?
答案 0 :(得分:0)
接近一个。如果将函数调用本身包装到$(document).ready
中,则可以避免重复的$(functionName)
块。例如:
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!");
}
};
接近两个。在关闭</body>
标记之前,将所有代码放在其余DOM内容之后。这样您就不必担心文档准备就绪,因为到目前为止脚本已经完成,HTML结构已经可用。