2013-12-14 21 views
0

当我运行这个JavaScript,我得到applyBefore没有定义。我只是有两个按钮与 onclick =“applyBefore();”在HTML中。这里是JS:函数没有定义,当它实际上是

(function(){ 

    $("div").css("border", "1px solid black"); 
    $("div").css("margin-top", "100px"); 
    $("div").css("margin-left", "50px"); 
    $("div").css("width", "100px"); 

    var input = $("input[text]").value; 
    var btnLeft = $("#btnLeft"); 

    function applyBefore() { 

     console.log("ne staa"); 

     var content = document.createElement("p"); 
     content.appendChild(document.createTextNode(input)); 
     $("div").prepend(content); 
     content.before$("#mainDiv"); 

     console.log("ne staa"); 
    } 

    function applyAfter() { 

    } 

}()); 
+1

这是什么? - >> content.before $(“#mainDiv”); – HICURIN

回答

6

你已经定义了另一个函数内的函数。因此它存在于该功能的范围内,而不是全球范围内。

请勿使用onclick属性。 Bind your event handlers with JavaScript,并且在您用来限制其他变量范围的匿名函数中这样做。

由于您使用jQuery:

jQuery('button').on('click', applyBefore); 

你可能想输入的值正确太(上DOM节点对象存在value财产,你有一个jQuery对象,以便使用val()方法),并在点击按钮时获取该值,而不是存储文档加载时的值。

+0

我真的很感谢,男人:)。我一般都是jQuery和javascript的新手,所以我尝试了约3个像addEventListener等的绑定,为了jQuery搜索了一些,但他们没有工作。谢谢! – user3023071

1

问题是您只在外部函数的范围内定义了这些函数。如果你想用它来事件直接在HTML绑定在<a onclick="applyBefore();">,你必须声明它们是功能外:

function applyBefore() { 
    var input = $("input[text]").val(); // Note the use of val() 

    ... 
} 

function applyAfter() { 

} 

(function(){ 
    $("div").css("border", "1px solid black"); 
    $("div").css("margin-top", "100px"); 
    $("div").css("margin-left", "50px"); 
    $("div").css("width", "100px"); 
}()); 

或者更好的是,摆脱了HTML事件绑定的和做的JavaScript的:

(function(){ 

    $("div").css("border", "1px solid black"); 
    $("div").css("margin-top", "100px"); 
    $("div").css("margin-left", "50px"); 
    $("div").css("width", "100px"); 

    input = $("input[text]").val(); // Note the use of val() 
    var btnLeft = $("#btnLeft"); 

    function applyBefore() { 
     ... 
    } 

    function applyAfter() { 
     ... 
    } 

    $("#myElement").on('click', applyBefore); // bind event here 
}()); 

另外,如果你想获得通过$("input[text]")返回输入元素(一个或多个)的值,你应该使用$("input[text]").val()或可能$("input[text]")[0].value,而不是仅仅$("input[text]").value

+0

呵呵,我以为我查过了。我必须失明。 – Quentin