Javascript preventDefault 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28686936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript preventDefault not working
提问by jumpman8947
Hi i'm just practicing some JavaScript and i came across an error i can't get around. I have a list in my html where each item links to a page, but i have a function in my js script where when i click the item its supposed to remove the item from the list, i'm trying to use preventDefault() but it still takes me to that link.
嗨,我正在练习一些 JavaScript,但遇到了一个我无法解决的错误。我的 html 中有一个列表,其中每个项目都链接到一个页面,但是我的 js 脚本中有一个函数,当我单击该项目时,它应该从列表中删除该项目,我正在尝试使用 preventDefault() 但是它仍然带我到那个链接。
<ul id="shoppingList">
<li class="complete"><a href="google.com><em>fresh</em>tuna</a></li>
<li class="complete"><a href="google.com">meatball</a></li>
<li class="complete"><a href="google.com">kiwi</a></li>
<li class="complete"><a href="google.com">chicken soup</a></li>
</ul>
function getTarget(e){
if(!e){
e = window.event;
}
return e.target || e.srcElement;}
function itemDone(e){
//Remove item from the list
var target;
var Parent;
var Grandparent;
target = getTarget(e);
Parent = target.parentNode;
Grandparent = target.parentNode.parentNode;
Grandparent.removeChild(Parent);
//Prevent the link from taking you somewhere
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
}
//Set up event listeners to call ItemDone() on click
var Shoppo = document.getElementById('shoppingList');
if(Shoppo.addEventListener){
Shoppo.addEventListener('click',function(e){
itemDone(e);
},flase);
}else{
Shoppo.attachEvent('onClick',function(e){
itemDone(e);
});
}
回答by VPK
To check if the e.preventDefault()
was called, you can use isDefaultPrevented
which returns true or false. So you can change your code like this,
要检查是否e.preventDefault()
被调用,您可以使用isDefaultPrevented
which 返回 true 或 false。所以你可以像这样改变你的代码,
e.preventDefault();
if(e.isDefaultPrevented()){
// default event is prevented
}else{
e.returnValue = false;
}
回答by Luke Digby
Change this :
改变这一点:
if(e.preventDefault){
e.preventDefault();
}else{
e.returnValue = false;
}
to this:
对此:
e.preventDefault();
return false;
This will work, and save you a couple of lines of code.
这将起作用,并为您节省几行代码。
回答by Revent
If you don't want the browser to follow the link but still need the url, you could store it in in a different attribute and set the href to #.
如果您不希望浏览器跟随链接但仍需要 url,您可以将其存储在不同的属性中并将 href 设置为 #。
<a href="#" id="link1" destinationurl="www.google.com" ... />
Then you could use the getAttribute function to retrieve the value
然后你可以使用 getAttribute 函数来检索值
document.getElementById("link1").getAttribute("destinationurl");