[英]How to get the remove button to work on this piece of code
This is an exercise from a test. 这是来自测试的练习。
I need to get the remove button working. 我需要使删除按钮正常工作。 I don't understand why the line 我不明白为什么行
document.getElementsByClassName("remove")[0].click();
is there either 有没有
Here is the code 这是代码
function setup() {
// Write your code here.
}
// Example case.
document.body.innerHTML = `
<div class="image">
<img src="someimage.jpg" alt="First">
<button class="remove">X</button>
</div>
<div class="image">
<img src="someimage.jpg" alt="Second">
<button class="remove">X</button>
</div>`;
setup();
document.getElementsByClassName("remove")[0].click();
console.log(document.body.innerHTML);
Edit: The expected output is that the remove button would remove the parent div (class="image") 编辑:预期的输出是删除按钮将删除父div(class =“ image”)
It doesn't work because the "remove' button doesn't have a callback function for the click
event defined for it. 它不起作用,因为“删除”按钮没有为其定义的click
事件的回调函数。
Also, this: document.getElementsByClassName("remove")[0]
should not be used as it causes a live node list to be created only to throw away that node list for just the first item in it. 另外,不应使用此document.getElementsByClassName("remove")[0]
: document.getElementsByClassName("remove")[0]
因为它会导致创建活动节点列表,而只是丢弃其中的第一项该节点列表。 Instead, document.querySelector(".remove")
should be used. 而是应使用document.querySelector(".remove")
。 See this other post of mine for details on this. 有关此细节,请参见我的另一篇文章 。
So, if we add a click
event handler and clean up your code it will work: 因此,如果我们添加一个click
事件处理程序并清理您的代码,它将起作用:
function setup() { // Write your code here. // This will set up a callback function for when the remove button gets clicked: theRemoveButton.addEventListener("click", function(){ console.log("You clicked the remove button!"); this.closest(".image").remove(); }); } // Example case. document.body.innerHTML = ` <div class="image"> <img src="someimage.jpg" alt="First"> <button class="remove">X</button> </div> <div class="image"> <img src="someimage.jpg" alt="Second"> <button class="remove">X</button> </div>`; var theRemoveButton = document.querySelector(".remove"); setup(); theRemoveButton.click(); // Forces the click event to fire on the button console.log(document.body.innerHTML);
I can't understand your problem but the 我无法理解您的问题,但是
document.getElementsByClassName("remove")[0].click();
line simulate a click on the first element of the with a css class called "remove", so it's useless because no event are attached to this element. 这行代码使用名为“删除”的css类模拟了对第一个元素的单击,因此它没有用,因为没有任何事件附加到该元素。 I think the addEventListener function is what your looking for. 我认为addEventListener函数是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.