我有这个代码片段:
function switchEvent() {
if (this.lastChild.tagName == "img" ) {
var remove = this.lastChild;
this.removeChild(remove);
}
else {
console.log(this.lastChild);
var image = document.createElement('img');
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在第二部分中,当我检查 console.log 时,它会打印出:
<img height="20" width="75" src="btn2.png" style="left: -14px; right: 0px;">
Run Code Online (Sandbox Code Playgroud)
它只是跳过“if”并跳转到“else”。呃,什么?
编辑:为了让您满意,这是一个 onclick 事件。因此,'this' 指的是被点击的元素。
我在这个问题上广泛浏览了互联网,包括stackoverflow。我的问题是我有一组“li”,当我使用 ctrl+click 手势时,我希望将多个“li”添加到数组中。我不断得到(e)没有定义。我发现了这个:在没有 keydown 事件的情况下检测 CTRL 和 SHIFT 键?
但是提供的答案似乎对许多人有用,但对我却不起作用。每当我使用它时,即使作为我脚本中的唯一项目,firebug 也不会在控制台中响应,但我得到:“ReferenceError: e is not defined。” 我正在使用 Firefox。
我最大的问题是将其添加到函数中,并且作为事件触发的函数可以区分 ctrl+click 和正常单击。
有什么专业知识可以帮助我吗?Vanilla Javascript 首选。
本练习的重点是在单击时删除 LI,但如果我按住 ctrl,我想一次删除多个。也许通过将它们存储在数组中。编辑:一些代码
<ul id = "ulItem">
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>
<script>
window.onload = function(){
var ulItem = document.getElementById("ulItem"); //gets UL with the "ulItem" ID.
var ulList = ulItem.getElementsByTagName("li"); //gets ulItem's "li" in an array.
///prepareLI function.///
var prepareLi = function(){
for(i = 0; i < ulList.length; i++){
ulList[i].addEventListener('click', elementClick);
}
}
//adds the same …Run Code Online (Sandbox Code Playgroud)