简体   繁体   English

在Javascript的document.ready处理程序中多次调用函数

[英]Calling A Function More than Once in Javascript's document.ready Handler

So I have a piece of code that most definitely relies on the DOM and needs to be executed after the page has loaded; 因此,我有一段代码绝对依赖于DOM,并且需要在页面加载后执行; if its not, a button's action is switched from performing javascript code (through a .click callback) to submitting the form. 如果不是,则按钮的操作从执行javascript代码(通过.click回调)切换为提交表单。 No idea why this is happening besides maybe somehow the DOM hasn't fully loaded and somehow the submit button at the bottom is mixed up with this other button inside the same form. 除了可能以某种方式未完全加载DOM以及以某种方式将底部的Submit按钮与同一表单内的另一个按钮混合在一起外,不知道为什么会这样。

Form code shown here (probably irrelevant): 此处显示的表单代码(可能不相关):

<form action="../landing/" method="POST">
    {% csrf_token %}
    <div class="ac_container">
        <div class="ui-widget">
            <button class="add_field_button">Add More Fields</button>
            <label for="tagsnodes">Tags: </label>
            <input id="tagsnodes" oninput = "myfunc('tagsnodes')" name="mytext" value="initial"/>
        </div>
    </div>
    <br><br>
    <input type="submit" value="Submit">
</form>

Anyway, when I call my function (which includes the .click callback) like so: 无论如何,当我调用函数(包括.click回调)时,如下所示:

$(document).ready(extrainput("nodes"));

the functionality of the "add_field_button" remains the same. “ add_field_button”的功能保持不变。

The extrainput() function: extrainput()函数:

function extrainput(extratype) {
            return function()
            {
                var max_fields      = 10; //maximum input boxes allowed
                var wrapper         = $(".ac_container"); //Fields wrapper
                var add_button      = $(".add_field_button"); //Add button ID

                var x = 1; //initlal text box count
                $(add_button).click(function(e){ //on add input button click
                    e.preventDefault();
                    if(x < max_fields){ //max input box allowed
                        x++; //text box increment
                        console.log("INSIDE");
                        var tid = "tags" + extratype + x
                        $(wrapper).append('<div class="ui-widget"><input id="'+tid+'" oninput = "myfunc(\'' + tid + '\')" name="mytext"/></div>');
                        myfunc(tid);
                    }
                });

                $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
                    e.preventDefault(); $(this).parent('div').remove(); x--;
                })
            }
        }

As you will notice, the function is written to return an anonymous function since that is what the document.ready takes. 您会注意到,该函数被编写为返回一个匿名函数,因为那是document.ready需要的。 I have to call the extrainput function like this, however. 但是,我必须像这样调用extrainput函数。 If I try to call it like this: 如果我尝试这样称呼它:

$(document).ready(function(){
    extrainput("nodes");
});

I get the same DOM error as if I had not waited for the page to be ready. 我收到相同的DOM错误,就像我没有等待页面准备就绪一样。

Once again, I would like to call the function in this way so that I could, say, make a call to "nodes" and a call to "edges." 再一次,我想以这种方式调用该函数,以便我可以调用“ nodes”和“ edges”。

myfunc code: myfunc代码:

function myfunc(tagid){
            try
            {
                var formData = {csrfmiddlewaretoken: "{{csrf_token}}", inputtext:document.getElementById(tagid).value};
            }
            catch (err)
            {
                var formData = {csrfmiddlewaretoken: "{{csrf_token}}", inputtext:""};
            }

            $.ajax({
                url: "../searchjson/",
                type: "post",
                data: formData,
                success: function(data){
                    var availableTags = data.replace(/"/g,"").replace('[','').replace(']','').replace(/, /g, ',').split(",");
                    $( "#"+tagid ).autocomplete({
                        source: availableTags
                    });
                },
                error:function(){
                    $("#result").html('There was error while submitting');
                }
            });
        }

This way of calling it is correct, though it seems like you tried it. 这种调用方式是正确的,尽管您似乎尝试过。

function extrainput(extratype) {

    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".ac_container"); //Fields wrapper
    var add_button = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    add_button.click(function (e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            console.log("INSIDE");
            var tid = "tags" + extratype + x
            wrapper.append('<div class="ui-widget"><input id="' + tid + 
                              '" oninput = "myfunc(\'' + tid + '\')" name="mytext"/></div>');
            myfunc(tid);
        }
    });

    wrapper.on("click", ".remove_field", function (e) { //user click on remove text
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })

}

$(document).ready(function () {
    extrainput("nodes");
});

I made a jsfiddle with this code. 我用这段代码做了一个jsfiddle。 What is the expected behavior which is missing? 缺少什么预期的行为? I seem to be able to add new text fields. 我似乎能够添加新的文本字段。

http://jsfiddle.net/mve9xzLx/1/ http://jsfiddle.net/mve9xzLx/1/

Also, since you define add_button as 另外,由于您将add_button定义为

var add_button = $(".add_field_button");

you don't need to wrap it in $() again, but that is unrelated. 您无需再次将其包装在$() ,但这无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM