无需 onclick 即可运行 Javascript 功能

1 javascript events function onclick

我有一个用于在网页上创建新表单元素的 Javascript 函数。该函数由 onclick 事件调用。

我不知道如何在没有 onclick 事件的情况下运行该函数。我需要这样做,因为我有 Python 代码生成内容来预填充表单元素,但仍然希望能够使用 Javascript 动态添加和删除表单元素。

Javascript函数:

    pcount = 0;
    createinputprice =function (){
        field_area = document.getElementById('pricetable');
        var tr = document.createElement("tr");
        var cella = document.createElement("td");
        var cellb = document.createElement("td");
        var input = document.createElement("input");
        var input2 = document.createElement("input");
        input.id = 'descprice'+pcount;
        input2.id = 'actprice'+pcount;
        input.name = 'descprice'+pcount;
        input2.name = 'actprice'+pcount;
        input.type = "text";
        input2.type = "text";
        cella.appendChild(input);
        cellb.appendChild(input2);
        tr.appendChild(cella);
        tr.appendChild(cellb);
        field_area.appendChild(tr);
        //create the removal link
        var removalLink = document.createElement('a');
        removalLink.onclick = function(){
            this.parentNode.parentNode.removeChild(this.parentNode)
        }
        var removalText = document.createTextNode('Remove Field');
        removalLink.appendChild(removalText);
        tr.appendChild(removalLink);
        pcount++
    }
Run Code Online (Sandbox Code Playgroud)

HTML:

<table id="pricetable">
</table>
<a href='#' onclick="createinputprice()">Add Price</a>
<script type="text/javascript">
    createinputprice();
</script>
Run Code Online (Sandbox Code Playgroud)

onclick 事件在 JSFiddle 中工作正常,但直接调用该函数根本不起作用。

小智 5

您可以使用 'onload' 事件将其放入标签中:

<body onload='yourfunction()'>
Run Code Online (Sandbox Code Playgroud)

或者只是使用jQuery:

$(document).ready(function() {
    yourFunc();
});
Run Code Online (Sandbox Code Playgroud)