2017-02-10 49 views
0

我有一個div什麼樣的按鈕(.butt),當我點擊它,它應該防止href重定向和打開輸入。它的劑量工作,它仍然重定向,當我從重定向返回輸入出現,但是當我按下輸入時,它仍然重定向。我怎樣才能防止href重定向onclick

我該如何做到這一點,以便當我按下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) { 
 
\t d.stopPropagation(); 
 
\t var x = $(d.target); 
 
\t x.html('<input id="edit2" style="width: 40px;" value="'+x.text()+'">'); 
 
\t var this_id = x.context.id; 
 
\t 
 
\t $("#edit2").on('blur', function(d) { 
 
\t \t if (h < 1) { 
 
\t \t \t h = h+1; 
 
\t \t \t d.stopPropagation(); 
 
\t \t \t 
 
\t \t \t $(d.target.parentElement).text(d.target.value); 
 
\t \t \t 
 
\t \t \t $.get(url, {id: this_id, value: d.target.value}) 
 
\t \t \t \t .done(function(d){ if(d == undefined || d != 1) { alert('Something went wrong, check your data and results. '+d);}}) 
 
\t \t \t \t .fail(function(d){ alert('error');}); 
 
\t \t \t $("#edit2").off('blur'); 
 
\t \t } 
 
\t \t 
 
\t \t 
 
\t }); \t 
 
\t 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>

回答

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(); 
 
\t d.stopPropagation(); 
 
\t var x = $(d.target); 
 
\t x.html('<input id="edit2" style="width: 40px;" value="'+x.text()+'">'); 
 
\t var this_id = x.context.id; 
 
\t 
 
\t $("#edit2").on('blur', function(d) { 
 
\t \t if (h < 1) { 
 
\t \t \t h = h+1; 
 
\t \t \t d.stopPropagation(); 
 
\t \t \t 
 
\t \t \t $(d.target.parentElement).text(d.target.value); 
 
\t \t \t 
 
\t \t \t $.get(url, {id: this_id, value: d.target.value}) 
 
\t \t \t \t .done(function(d){ if(d == undefined || d != 1) { alert('Something went wrong, check your data and results. '+d);}}) 
 
\t \t \t \t .fail(function(d){ alert('error');}); 
 
\t \t \t $("#edit2").off('blur'); 
 
\t \t } 
 
\t \t 
 
\t \t 
 
\t }); \t 
 
\t 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>

相關問題