使用 “this.id” 在 JavaScript 中添加事件监听器。

huangapple go评论73阅读模式
英文:

Use "this.id" when addEventListener in JavaScript

问题

Here's the translated code snippet:

我想在 JavaScript 中获取点击时创建的元素的 ID

例如

var input_check = document.createElement("INPUT");
input_check.id = 1;
input_check.type = "checkbox";
input_check.addEventListener("click", test);

// 当单击复选框时执行此函数
function test(id) {
    console.log(id);
}

显然根据此示例我无法打印 "ID"因为我需要使用 JavaScript 生成类似以下的内容

<input id="1" type="checkbox" onClick="test(this.id)">

通过上述示例我得到了类似以下的内容

<input id="1" type="checkbox" onClick="test()">

请注意,翻译已经在代码部分进行了标记,不包括问题和其他内容。

英文:

I want to get the id of an element create in javascript when we click on him.

For example:

	var input_check  = document.createElement(&quot;INPUT&quot;);
	input_check.id = 1;
	input_check.type = &quot;checkbox&quot;;
	input_check.addEventListener(&quot;click&quot;, test);


	//Come here when s1 click on the checkbox
    function test(id){
	    console.log(id);
    }

Obviously with this example I can't print "ID" cause I need to "generate" with javascript something like this :

&lt;input id=&quot;1&quot; type=&quot;checkbox&quot; onClick=&quot;test(this.id)&quot;&gt;

With the previous example I have something like this :

&lt;input id=&quot;1&quot; type=&quot;checkbox&quot; onClick=&quot;test()&quot;&gt;

答案1

得分: 2

将代码中的英文部分翻译为中文:

// 将onclick函数写成属性值时,执行与之前完全相同的操作。
input_check.addEventListener("click", function () {
    test(this.id);
});

// 或者只需写`test`,期望它作为事件监听器首先被调用:
input_check.addEventListener("click", test);
function test(event) {
    console.log(this.id);
}
英文:

Do exactly what you did when writing the onclick function as an attribute value.

input_check.addEventListener(&quot;click&quot;, function () {
    test(this.id);
});

Or just write test to expect to be called as an event listener in the first place:

input_check.addEventListener(&quot;click&quot;, test);
function test(event) {
    console.log(this.id);
}

答案2

得分: -2

将输入内容生成为HTML,您必须将您创建的输入添加到body中,就像这样:

document.body.appendChild(input_check);

英文:

To generate the input in HTML, you must add the input you created to the body, like this:

document.body.appendChild(input_check);

huangapple
  • 本文由 发表于 2020年1月7日 00:33:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615699.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定