javascript — функция Jquery / Ajax Drag n Drop для щелчка

Прежде всего, посмотрите на эту демонстрацию: http://demo.tutorialzine.com/2009/09/shopping-cart-php-jquery/demo.php
взято с tutorialzine.com

я уже взял это и использовал в своем проекте сейчас, корзина. без ошибок до сих пор перетащить капля действительно мило. что я пытаюсь сделать, это то, что элементы / продукты также могут быть кликабельными. Я все еще новичок в jquery / ajax, поэтому мне так сложно сделать его кликабельным, а не перетаскивать его в корзину.

Вот код внутри script.js, который содержит функцию перетаскивания:

var purchased=new Array();  //an array containing all the products we've purchased so far
var totalprice=0;   //the total price

$(document).ready(function(){

$('.product').simpletip({   //using the simpletip plugin

offset:[40,0],
content:'<img style="margin:10px;" src="img/ajax_load.gif" alt="loading" />',   // default content
onShow: function(){

var param = this.getParent().find('img').attr('src');
// fix for IE6
if($.browser.msie && $.browser.version=='6.0')
{
param = this.getParent().find('img').attr('style').match(/src=\"([^\"]+)\"/);
param = param[1];
}

// after the tooltip is shown, load the tips.php file and pass the image name as a parameter
this.load('ajax/tips.php',{img:param});
}

});

$(".product img").draggable({   // enable all product images to be dragged

containment: 'document',
opacity: 0.6,
revert: 'invalid',
helper: 'clone',
zIndex: 100

});

$("div.content.drop-here").droppable({  // convert the shopping cart to a droppable

drop:
function(e, ui)
{
var param = $(ui.draggable).attr('src');
// IE6 fix
if($.browser.msie && $.browser.version=='6.0')
{
param = $(ui.draggable).attr('style').match(/src=\"([^\"]+)\"/);
param = param[1];
}

addlist(param); // the special addlist function - see below
}

});

});

вторая часть script.js:

function addlist(param)
{
// the addlist function ads a product to the shopping cart

$.ajax({    // sending an ajax request to addtocart.php
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param), // the product image as a parameter
dataType: 'json',   // expecting json
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');},    // showing the loading gif
success: function(msg){

$('#ajax-loader').css('visibility','hidden');   // hiding the loading gif animation
if(parseInt(msg.status)!=1)
{
return false;   // if there has been an error, return false
}
else
{
var check=false;
var cnt = false;

for(var i=0; i<purchased.length;i++)
{
if(purchased[i].id==msg.id) // find if we have already bought this prduct
{
check=true;
cnt=purchased[i].cnt;

break;
}
}

if(!cnt)    // if we haven't bought it yet, or we have removed it from the purchases, we insert it in the shopping cart
$('#item-list').append(msg.txt);

if(!check)  // if we haven't bought it yet, insert it in the purchased array
{
purchased.push({id:msg.id,cnt:1,price:msg.price});
}

else    // else if we've bought it
{
if(cnt>=3) return false;    // 3 products of type max

purchased[i].cnt++;
$('#'+msg.id+'_cnt').val(purchased[i].cnt); // update the select box
}

totalprice+=msg.price;  // recalculate the price
update_total(); // update the total div

}

$('.tooltip').hide();   // hiding the tooltip (sometimes it stays on screen after the drag)

}
});
}

function findpos(id)    // a helper function that finds the position at which the product is inserted in the array, returns the position
{
for(var i=0; i<purchased.length;i++)
{
if(purchased[i].id==id)
return i;
}

return false;
}

function remove(id) // remove a product from the shopping cart
{
var i=findpos(id);  // find its position in the array

totalprice-=purchased[i].price*purchased[i].cnt;    // recalculate the price
purchased[i].cnt = 0;   // reset the counter

$('#table_'+id).remove();   // remove it from the cart
update_total(); // update the total price counter on the page
}

function change(id) // evoked when we change the number of products via the select area
{
var i=findpos(id);

totalprice+=(parseInt($('#'+id+'_cnt').val())-purchased[i].cnt)*purchased[i].price;

purchased[i].cnt=parseInt($('#'+id+'_cnt').val());
update_total();
}

function update_total() // function that updates the total price div on the page
{
if(totalprice)
{
$('#total').html('total: $'+totalprice);    // if we've bought somehitng, show the total price div and the purchase button
$('a.button').css('display','block');
}
else    // hide them
{
$('#total').html('');
$('a.button').hide();
}
}

Помимо функции перетаскивания, я также хочу сделать элемент кликабельным, нажмите на элемент / продукт, и он появится в корзине 🙁 любая возможная помощь .. спасибо заранее

0

Решение

На мой взгляд, вам придется выбирать между перетаскиванием & падение и поведение щелчка.
Попытка реализовать и то, и другое может сбить с толку ваших пользователей и сделать ваш код трудным для адаптации. Но чтобы ответить на ваш вопрос, вот как вы можете сделать, чтобы активировать щелчок на ваших элементах:

Лучшим вариантом будет установить ссылку на ваше изображение:

<a href="addToCart.php?id=78"><img.....></a>

Это может работать в AJAX.

Если вы все еще хотите реализовать оба перетаскивания & перетаскивая и щелкая, вы должны рассмотреть раздельное отображение двух функций: одна зона для включения перетаскивания, а другая для непосредственного добавления товара в корзину:

<img ... alt="click to drag !"><br>
<a href="#">Click to add to cart !</a>
1

Другие решения

спасибо за ответы ребята. хотя я не получил xD

но..

Я понял это! ура!

это одна для функции щелчка:

$ (‘. product img’). click (function () {
var param = $ (this) .attr (‘src’); если ($. browser.msie && $ .browser.version == ‘6.0’) {param = $ (this) .attr (‘style’). match (/ src = \ «([^ \»] +) \ «/); param = param [ 1];}
addlist (пары); });

теперь это и кликабельно, и перетаскиваемо: D

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector