gpt4 book ai didi

javascript - 外部文件中未触发点击事件

转载 作者:行者123 更新时间:2023-11-27 23:56:30 25 4
gpt4 key购买 nike

我正在尝试创建一个可以在我的所有 html 页面上使用的库代码。我对 JS 很陌生,这是我尝试像库函数一样编写的第一个代码。

我有一个文本字段和它旁边的一个按钮,单击该按钮时会在下面添加另一个文本字段和它旁边的一个按钮,这也会删除上一行中的按钮。

我设法在同一行中创建一个按钮,并在下一行中添加文本字段,但是新添加的方法的按钮单击不适用于纯 JS,因此我尝试使用 jquery“on”单击事件。由于某种原因,在我的情况下它没有被触发。不确定我错过了什么。

外部文件中的代码

var addAnother = {
addAnotherField: function (eventTrigger, fieldContainer, arrayField) {
console.log("called");
var eventTrigger = eventTrigger;
console.log("ready called", eventTrigger);
$(document).on('click', eventTrigger, function (e) {
console.log("click called");
var buttonText = this.value;
var div = document.getElementById(fieldContainer);
var element = document.getElementById(eventTrigger);
element.parentNode.removeChild(element);
var input = document.createElement("input");
input.type = "text";
input.name = arrayField;
div.appendChild(document.createElement("br"));
div.appendChild(input);
var button = document.createElement("input");
button.type = "button";
button.id = eventTrigger;
button.value = buttonText;
div.appendChild(button);
});
}
}

HTML 代码

$(document).ready(function () {
addAnother.addAnotherField("addAnother", "addAnotherContainer", "fieldArray[]");
});

工作 JS 代码: http://jsfiddle.net/balasivagnanam/ekoob8f0/

下一个按钮非工作代码 JS http://jsfiddle.net/balasivagnanam/ukseeuak/

使用 Jquery: http://jsfiddle.net/balasivagnanam/6ea2dk6m/

最佳答案

这是你想要的吗:

/** this part will be located in another file added as a js library */
function addAnother(elem) {
var text = $("#addAnotherField").clone();
$("<br/>").insertBefore($("#addAnother"));
text.insertBefore($("#addAnother"));

}
/* this part will be coded below the above code file in the html file*/

$(document).ready(function () {
$('#addAnother').click(function () {
addAnother(this);
});
});

Here is the JSFiddle demo

关于javascript - 外部文件中未触发点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223322/

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