如何使用jquery live创建一个函数?

时间:2010-06-03 21:00:42

标签: ajax jquery

我正在编写一个功能,可以在用户添加到购物车时将用户保留在灯箱图像中。

单击任何图像时,使用灯箱v2进行放大,因此当用户单击“添加图像”时,它将刷新页面。当我在jcart支持时询问它时,他们告诉我使用jquery live,但我不知道该怎么做。 T尝试了这段代码,但仍然没有发生任何事情:

        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 个答案:

答案 0 :(得分: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这样的插件使这更容易一些。

最终结果是表单元素被填充到要发送到脚本的对象中。