我正在尝试将事件处理程序添加到div中具有图像的div。我的问题是,只有双击它旁边的div之外,该事件才有效。当您双击div内的图片时,它不会触发事件。我该怎样做才能使事件双向发挥作用?
HTML
<div id="placeholder">
<a href="http://google.com" target="_blank">
<img src="http://www.fat-animals.com/wp-content/uploads/2009/03/11.jpg" alt="" />
</a>
</div>
的javascript
var pic;
pic = document.getElementById("placeholder");
pic.ondblclick = function() {
pic.innerHTML = "blocked!";
}
答案 0 :(得分:5)
检查这个小提琴 http://jsfiddle.net/unloco/9DWrN/3/
var pic = document.getElementById("placeholder");
var clicked = false;
pic.onclick = function() {
if(clicked) {
pic.innerHTML = "blocked!";
} else {
clicked = true;
}
setTimeout(function(){
clicked = false
}, 333); //detect fast clicks (333ms)
}
答案 1 :(得分:1)
您当前的解决方案确实有效,但它似乎并不像,因为您被重定向到新页面。
如果您有Chrome(可能是Firefox,甚至可能是IE 8+),请双击图像(在新标签/窗口中打开)。您的活动仍会被解雇。然后,您可以继续阻止对这些事件的默认。
使用双击事件并不是防止恶意点击的最佳选择,因为双击事件只会在每两次点击时被抛出。虽然客户端验证不利于防止恶意点击,但最好使用点击事件并使用计时器进行检查(即将事件限制为每200毫秒一次的最大值,或者仅在没有先前点击的情况下允许它在之前的200毫秒内。
答案 2 :(得分:0)
那么在onclick上更改pic.innerHTML
呢?
var = document.getElementById("placeholder");
pic.onclick = function() {
pic.innerHTML = "blocked!";
alert('The link has been blocked');
}
即使您删除了该链接,也会遵循该时间。
另见http://jsfiddle.net/4Kecd/1/。
你可以......
var pic1 = document.getElementById("placeholder1"),
clicked1=false;
pic1.onclick = function() {
if(clicked1){
alert("The link has been deleted. You can't follow the link twice!");
}else{
pic1.innerHTML = pic2.getElementsByTagName('a')[0].innerHTML;
alert('The link has been deleted.\nHowever, the new tab will be opened when you accept this alert.');
clicked1=true;
}
}
...如果您想删除链接,但想要图像。
或者你可以禁用链接:
var pic2 = document.getElementById("placeholder2"),
clicked2=false;
pic2.onclick = function(e) {
var a=pic2.getElementsByTagName('a')[0];
if(clicked2){
alert("The link has been disabled. You can't follow the link twice!");
a.href="#";/* Nonsense since we have disabled the link,
but we want to ensure that the link isn't followed*/
}else{
clicked2=true;
a.onclick=function(){return false;}
alert('The link has been disabled.\nHowever, the new tab will be opened when you accept this alert.');
}
}
注意:UnLoCo的解决方案很好,但问题是它不会阻止我们跟踪链接。
相反,您可以在第一次单击时禁用链接,并在几秒钟后启用它:
var pic = document.getElementById("placeholder"),
clicked=false;
pic.onclick = function(e) {
var a=pic.getElementsByTagName('a')[0];
if(clicked){
alert("The link has been disabled. You can't follow the link twice!");
a.href="#";
}else{
clicked=true;
a.onclick=function(){return false;}
if(!a.getAttribute('data-href')){
a.setAttribute('data-href',a.href);
}
alert('The link has been disabled.\nHowever, the new tab will be opened when you accept this alert.');
setTimeout(function(){enableLink(a);},5000);
}
}
function enableLink(a){
a.href=a.getAttribute('data-href');
a.onclick=function(){return true;}
clicked=false;
}
请在此处查看:http://jsfiddle.net/4Kecd/2/