2010-06-03 49 views
0

我正在寫一個函數,以便在添加到購物車時將用戶保存在燈箱圖像中。如何用jquery live創建一個函數?

當你點擊任何圖片時,它使用lightbox v2很好地放大,所以當用戶點擊添加圖片時,它會刷新頁面。當我在jcart支持中詢問它時,他們告訴我要使用jquery live,但我不知道如何做到這一點。牛逼嘗試這種代碼,但仍然什麼也沒有發生:

 jQuery(function($) { 

$('#button') 
    .livequery(eventType, function(event) { 
     alert('clicked'); // to check if it works or not 
     return false; 
    }); 
}); 

我也用

jQuery(function($) { 

$('input=[name=addto') 
    .livequery(eventType, function(event) { 
     alert('clicked'); // to check if it works or not 
     return false; 
    }); 
}); 

但毫無效果。

的代碼來創建這些圖像http://pasite.org/code/572

我也試過:

function adding(form){ 
$("form.jcart").livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}           
}); 
return false;           
} 

,它似乎增加jcart但但它仍然刷新

回答

1

.live()是指定處理程序到未來的創造元素。但是,在您的網站上,您正在重新加載頁面,因此.live不會有任何影響。 (您正在提交表單)

聽起來好像你想做一個ajax請求將項目添加到購物車並更新網站上的顯示?這將在提交表單中,如果jcart是動態創建的,那麼是的,live是答案。

$('.jcart').live('submit', function() { 
    // aggregate form elements into object and send via ajax 
    // update the cart on the page, since we haven't reloaded the page the light box is still displayed 
}); 

關於評論:

當你發送一個Ajax請求,jQuery的需要一個對象作爲參數。如$.post('urlToPostTo.php', { title: 'title of whatever', id: 5 });

服務器認爲這等同於:

<form id="myForm" action="uroToPostTo.php" method="POST" > 
    <input type="text" name="title" value="title of whatever" /> 
    <input type="hidden" name="id" value="5" /> 
    <input type="submit" name="submit" value="submit" /> 
</form> 

所以,如果你的表單輸入聚合成一個對象,有幾個方法(甚至一些jQuery插件來幫助你)。原始的方式是:

var $form = $('#myForm'); // instead of finding myForm over and over, cache it as a variable to use 
var objToSend = {}; 
objToSend.title = $form.find('input[name=title]').val(); 
objTosend.id = $form.find('input[name=id]').val(); 
$.post('urlToPostTo.php', objToSend); 

更優雅的解決方案是讓東西遍歷所有表單元素並將它們放入一個對象中。像http://docs.jquery.com/Plugins:Forms這樣的插件可以讓你更容易一些。

最終結果是表單元素被塞入到一個對象中發送到您的腳本。

+0

@丹Heberden我是一個新手你是什麼意思聚合形式元素到對象和發送通過ajax – Mahmoud 2010-06-03 21:34:05

+0

更新回答給你。過去,我會研究製作ajax表單的好方法,在你發送數據之前檢查數據,形成驗證的工作方式,這種東西。 – 2010-06-06 18:27:50

+0

@丹Heberden我已經成功地停止燈箱退出,但形式沒有提交給jcart我所做的只是簡單地添加旁邊的形式'onsubmit ='返回false'',但這導致表單不被引用到jcart – Mahmoud 2010-06-06 21:23:47

相關問題