【问题标题】:How can I prevent href redirect onclick如何防止 href 重定向 onclick
【发布时间】:2017-02-10 19:23:08
【问题描述】:

我有一个类似于按钮(.butt)的 div,当我单击它时,它应该防止 href 重定向并打开输入。它不起作用,它仍然会重定向,当我从重定向返回时,会出现输入,但是当我按下输入时,它仍然会重定向。

我怎样才能做到这一点,当我按下我的 div 时,它会禁用重定向并让我在输入中插入一个值来更改值?

var x;
var h = 0; // blur fires multiple times, use h to count and fire once
var url = 'up.php';

$(".butt").on('click', function(event) { 
event.preventDefault();
$(".tk").on('click', function(d) { 
	d.stopPropagation();
	var x = $(d.target); 
	x.html('<input  id="edit2" style="width: 40px;" value="'+x.text()+'">'); 
	var this_id = x.context.id;
	
	$("#edit2").on('blur', function(d) { 
		if (h < 1) {
			h = h+1;
			d.stopPropagation();
			
			$(d.target.parentElement).text(d.target.value);
			
			$.get(url,  {id: this_id, value: d.target.value})
				.done(function(d){ if(d == undefined || d != 1) { alert('Something went wrong, check your data and results. '+d);}})
				.fail(function(d){ alert('error');});
			$("#edit2").off('blur');
		}
		
		
	});	
	h = 0;
});
});
.butt{width:15px;height:15px; background-color:red;border-radius: 50%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="butt"> </div>
<a href="http://www.google.com" class="tk">click</a>

【问题讨论】:

    标签: javascript jquery html redirect href


    【解决方案1】:

    你可以使用preventDefault

    event.preventDefault() 方法停止默认行为 元素发生。

    d.preventDefault();
    

    var x;
    var h = 0; // blur fires multiple times, use h to count and fire once
    var url = 'up.php';
    
    $(".butt").on('click', function(d) { 
    $(this).on("click", function(){return false;})
    $(".tk").on('click', function(d) { 
        d.preventDefault();
    	d.stopPropagation();
    	var x = $(d.target); 
    	x.html('<input  id="edit2" style="width: 40px;" value="'+x.text()+'">'); 
    	var this_id = x.context.id;
    	
    	$("#edit2").on('blur', function(d) { 
    		if (h < 1) {
    			h = h+1;
    			d.stopPropagation();
    			
    			$(d.target.parentElement).text(d.target.value);
    			
    			$.get(url,  {id: this_id, value: d.target.value})
    				.done(function(d){ if(d == undefined || d != 1) { alert('Something went wrong, check your data and results. '+d);}})
    				.fail(function(d){ alert('error');});
    			$("#edit2").off('blur');
    		}
    		
    		
    	});	
    	h = 0;
    });
    });
    .butt{width:15px;height:15px; background-color:red;border-radius: 50%;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="butt"> </div>
    <a href="http://www.google.com" class="tk">click</a>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2018-01-21
      • 2012-06-24
      • 2016-10-06
      • 2019-02-26
      • 2020-01-07
      • 1970-01-01
      相关资源
      最近更新 更多