为带变量的函数动态添加事件侦听器
dynamically add event listener for function with variable
我正在尝试创建一个选项来向我的网站添加其他复选框/文本字段。 我有一个按钮"+"链接到一个函数,该函数创建按数字顺序命名的字段。 我想在复选框中添加一个事件侦听器,该复选框将根据调用它的复选框的名称调用需要唯一变量的函数。
<div id="container">
<input name="+" type="button" id="+" onclick="addInput()" value="+" label="+" />
</div>
<p id=demo>eeeeeeee</p>
var countBox = 1;
function addInput () {
var breakNode = document.createElement("br");
breakNode.className = countBox.toString();
//create checkbox
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.value = "ProgramSpecificBox" + countBox.toString();
checkbox.name = "ProgramSpecificBox" + countBox.toString();
checkbox.id = "ProgramSpecificBox" + countBox.toString();
//create Amount
var Amount = document.createElement("input");
Amount.type = "number";
Amount.value = countBox.toString();
Amount.name = "ItemCostVis"+ countBox.toString();
Amount.id = "ItemCostVis" + countBox.toString();
var container = document.getElementById('container');
container.appendChild(breakNode);
container.appendChild(checkbox);
container.appendChild(Amount);
checkbox.addEventListener("click", function () {
testthis(NEED CODE HERE);
})
countBox += 1;
}
function testthis (text) {
document.getElementById("demo").innerHTML = text;
}
我应该放什么而不是"这里需要代码"来获得与调用函数的复选框的 id 相同的内容?
而不是:
checkbox.addEventListener("click", function()
{testthis(NEED CODE HERE);
})
countBox += 1;
}
尝试:
checkbox.addEventListener("click", function(e)
{testthis(e);
})
countBox += 1;
}
e 参数应该是事件对象。事件对象具有一个属性 currentTarget,该属性引用初始化事件的元素。因此,您可以调用:
function testthis(e)
{
var myvar = e.currentTarget.id;
}
有关示例,请参阅此小提琴。
你可以尝试这样的事情:
checkbox.onclick = function(me){window.alert(me.id)};
相关文章:
- 如何在for循环中添加事件侦听器
- 如果选中了多个复选框,如何添加事件
- 正在ng重复元素上添加事件
- 在动态创建的标记上添加事件
- 如何在HTML列表中添加事件's子弹
- 将事件侦听器添加到文档,而不是签入元素存在,然后添加事件侦听器
- jQuery完整日历添加事件,仅包含月份和日期
- 是否可以在数字输入框中的小按钮中添加事件侦听器
- 在Google Chrome扩展中添加事件侦听器
- AngularJS:在.post()之后添加事件侦听器
- 对象 Javascript 中的标签无效 - 想要添加事件列表器
- 添加事件侦听器不起作用
- 如何为angular js条形图添加事件
- 在 http 请求中添加事件侦听器 ( request.on ) 是什么意思?而笏就是它的用途
- Iron:路由器在更改路由器上添加事件
- 如何为表行结果的每个按钮添加事件侦听器
- 在 javascript 中添加事件处理程序的位置
- YouTube API-动态添加事件侦听器
- 在聚合物的子菜单标题中添加事件
- 检查是否可以添加事件侦听器而不添加