gpt4 book ai didi

javascript - 在没有 onclick 的情况下运行 Javascript 函数

转载 作者:行者123 更新时间:2023-12-05 01:03:05 25 4
gpt4 key购买 nike

我有一个用于在网页上创建新表单元素的 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();
});

关于javascript - 在没有 onclick 的情况下运行 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com