[英]No refresh or page reload using JS
我在Rails 4應用程序中有一個Ajax請求,但是一旦單擊按鈕,它就會重新加載整個頁面。 我怎樣才能避免這種情況發生? 該頁面已緩存,因此我不能簡單地添加link_to或button_to。 提前致謝。
listing_collection.js
$(document).ready(function(){
$(".listcollect").on("click", function(){
var listID = this.id;
$.ajax({
method: "GET",
url: "/listing_collections/:id/listcollect",
success: function(result) {
var arrLen = result.length
var $ul = $("<ul></ul>")
for (var i = 0; i<arrLen; i++){
var $li = $("<li></li>");
var $a = $("<a></a>");
$a.attr("href", "/listings/" + listID + "/add_to_collection?listing="+listID+"$amp;listing_collection_id="+result[i]["id"]+"&listing_id="+listID)
$a.text(result[i]["name"])
$li.append($a)
$(this).next().append($li)
}
}.bind(this)
})
});
});
這是按鈕:
<div class="btn-group listcollect-wrapper">
<button class="listcollect button btn-blue-white btn-2x dropdown-toggle" data-toggle='dropdown' type="button" id=<%= listing.id %>>Add to Listing Collection <span class="caret"></span></button>
<ul class='dropdown-menu'>
</ul>
</div>
我的兩分錢.listcollect
這個類的dom是一個類型為.listcollect
的按鈕,即button type="submit"
您可以使用button type = "button"
或使用
event.preventDefault()
$(".listcollect").on("click", function(){
event.preventDefault()
// Rest of code
})
這是因為這是定位標記的默認行為。 如建議的那樣,您可以將控件類型更改為類似button的類型,也可以覆蓋默認行為,如下所示:
$(".listcollect").on("click", function(e){
e.preventDefault();
});
嘗試這個:
$(document).ready(function(){
$(".listcollect").on("click", function(e){
e.preventDefault();
e.stopPropagation();
var listID = this.id;
$.ajax({
method: "GET",
url: "/listing_collections/:id/listcollect",
success: function(result) {
var arrLen = result.length
var $ul = $("<ul></ul>")
for (var i = 0; i<arrLen; i++){
var $li = $("<li></li>");
var $a = $("<a></a>");
$a.attr("href", "/listings/" + listID + "/add_to_collection?listing="+listID+"$amp;listing_collection_id="+result[i]["id"]+"&listing_id="+listID)
$a.text(result[i]["name"])
$li.append($a)
$(this).next().append($li)
}
}.bind(this)
})
});
});
我添加了e.preventDefault()和e.stopPropagation()來阻止瀏覽器默認處理單擊事件,而e.stopPropagation()禁止將click事件傳播到控件的容器,以防它們也具有偵聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.