运行Javascript函数而不点击

Run Javascript function without onclick

本文关键字:Javascript 函数 运行      更新时间:2023-09-26

我有一个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++
    }

.HTML:

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

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

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

<body onload='yourfunction()'>

或者只使用 jQuery:

$(document).ready(function() {
    yourFunc();
});
我想

你可以使用<body onload="yourfunction()">你也应该研究 http://www.w3schools.com/js/js_htmldom_events.asp。

正如你所看到的,javascript中有很多可用的事件,应该选择正确的工具(事件)来完成这项工作。

如果你想在

页面加载时调用jquery函数:你可以使用$(document).ready(function(){});

例如:

J查询-

<script type="text/javascript">
    $(document).ready(function(){
       createinputprice();
    });
 </script>

你也可以在 Jquery 中触发 click 事件:

.HTML-

<a id="myLink" href='#' onclick="createinputprice();">Add Price</a>

J查询-

 <script type="text/javascript">
     $(document).ready(function(){
          $('#myLink').click();
     });
 </script>