功能未定义,实际上是

时间:2013-12-14 15:49:16

标签: javascript function

当我运行这个javascript时,我得到applyBefore未定义。我只有2个按钮 的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() {

    }

}());

2 个答案:

答案 0 :(得分:6)

您已在另一个函数中定义了该函数。因此,它存在于该职能范围内,而不是全球范围。

不要使用onclick属性。 Bind your event handlers with JavaScript,并在您用来限制其他变量范围的匿名函数中执行此操作。

因为你正在使用jQuery:

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

您可能也希望正确获取输入的值(DOM节点对象上存在value属性,您有一个jQuery对象,因此使用val()方法)并获取该值< em>单击按钮时而不是存储文档加载时的值。

答案 1 :(得分: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