Что бы сделать в своей позиции, вместо того, три различных класса (bag1
, bag2
, bag3
), я создаст новый класс под названием bag
и дать каждому из пакетов этот класс, а затем указать любой другой CSS, специфичный для каждого из них в другом классе, который называется one
, two
и three
. Так, например, первый мешок станет <div class="bag two" style="...
. Я бы тогда добавить функцию JQuery, как этот
$('.bag').click(function() {
if($('.selected').length > 0 && !$(this).hasClass('selected'))
{ // Checks to see if there is a selected and if the clicked one is selected
$('.selected').removeClass('selected');
$(this).addClass('selected');
}
else if($(this).hasClass('selected')) {
// Allows a bag to be toggled when clicked
$(this).removeClass('selected');
}
else {
// If there is no bag `selected` then make the clicked one selected
$(this).addClass('selected');
}
});
, а также создать некоторые CSS для selected
класса для пользователей, чтобы знать, какой из них щелкают
.selected {
background-color: #FFFF00;
}
Затем вы можете установить правила или нет что-то можно перетаскивать или нет на основе selected
. Эта часть является псевдокодом
if($('.bag.one').hasClass('selected'))
{
// Allow things to be dragged to only bag one
}
if($('.bag.two').hasClass('selected'))
{
// Allow things to be dragged only to bag two
}
if($('.bag.three').hasClass('selected'))
{
// Allow things to be dragged only to bag three
}
Ваш код слишком массивный, чтобы мы могли реализовать все это для вас. Это должно дать правильное направление.Прокомментируйте, пожалуйста, если есть что-нибудь еще я могу помочь вам с
----- ГИГАНТСКИЙ EDIT -----
(я не работал так тяжело на исправление вашей ситуации, но Я плохо себя чувствую за свою позицию, поэтому я сделал это)
После некоторых серьезных изменений в исправлении форматирования вашего кода, оптимизации его для повторного использования (и удаления сотен строк ненужного кода в процессе), перемещение выражений if, которые я создал ранее в setInterval
, чтобы проверить, обновлять ли он текущую информацию и исправлять большую часть вашего плохого CSS, Я придумал this rough update
Вот код для этого:
<!-- HTML -->
<div id="body">
<div class="bag one">
Bag 1
<img src="images/sb1.jpg" height="50" width="50" />
</div>
<div class="bag two">
Bag 2
<img src="images/sb2.jpg" height="50" width="50" />
</div>
<div class="bag three">
Bag 3
<img src="images/sb3.jpg" height="50" width="50" />
</div>
<div class="products" style="width: 120px; height: 100px; left: 23px; top: 120px;">
<ul>
<li> <a href="#" class="item one">
<img src="images/shirt2.gif" height="45" width="45"/>
<div>
<p>item1_1</p>
<p>Price:$25</p>
</div>
</a>
</li>
</ul>
</div>
<br>
<div class="products" style="width: 120px; height: 100px; left: 30px; top: 225px;">
<ul>
<li> <a href="#" class="item two">
<img src="images/shoes1.gif" height="45" width="45"/>
<div>
<p>item2_1</p>
<p>Price:$30</p>
</div>
</a>
</li>
</ul>
</div>
<div class="products" style="width: 120px; height: 144px; left: 34px; top: 342px;">
<ul>
<li> <a href="#" class="item three">
<img src="images/shirt2.gif" height="45" width="45"/>
<div>
<p>item3_1</p>
<p>Price:$25</p>
</div>
</a>
</li>
</ul>
</div>
<br>
<div class="cart" style="left: 200px; top: 150px; height: 300px; width: 237px">
<div class="ctitle">Shopping Cart</div>
<div style="background:#fff">
<table id="cartcontent1" fitColumns="true" style="width1:300px;height:auto;">
<thead>
<tr>
<th field="name" width=140>Name</th>
<th field="quantity" width=60 align="right">Quantity</th>
<th field="price" width=60 align="right">Price</th>
<th field="remove" width=60 align="right">Remove</th>
</tr>
</thead>
</table>
</div>
<p class="total">Total: $0</p>
<div class="ctitle" style="position:absolute;bottom:10px"></div>
</div>
</div>
<!-- CSS -->
.bag {
width:80px;
float:left;
text-align:center;
}
.products {
position:fixed;
height:100%;
background:#fafafa;
}
.products ul {
list-style:none;
margin:0;
padding:0px;
}
.products li {
display:inline;
float:left;
margin:10px;
}
.item {
display:block;
text-decoration:none;
}
.item img {
border:1px solid #333;
}
.item p {
margin:0;
font-weight:bold;
text-align:center;
color:#c3c3c3;
}
.cart {
position:absolute;
width:260px;
height:100%;
background:#ccc;
padding:0px 10px;
}
.ctitle {
text-align:center;
color:#555;
font-size:18px;
padding:10px;
}
.auto-style3 {
float: right;
position: relative;
width: 260px;
height: 100%;
background: #ccc;
padding: 0px 10px;
margin-bottom: 0px;
}
.selected {
background-color: #FFFF00;
}
<!-- Javascript/jQuery-->
var data = {
"total": 0,
"rows": []
};
var totalCost = 0;
$(document).ready(function() {
$('#cartcontent1').datagrid({
singleSelect: true
});
$('.item').draggable({
revert: true,
proxy: 'clone',
onStartDrag: function() {
$(this).draggable('options').cursor = 'not-allowed';
$(this).draggable('proxy').css('z-index', 10);
},
onStopDrag: function() {
$(this).draggable('options').cursor = 'move';
}
});
$('.bag').click(function() {
if ($('.selected').length > 0 && !$(this).hasClass('selected')) { // Checks to see if there is a selected and if the clicked one is selected
$('.selected').removeClass('selected');
$(this).addClass('selected');
} else if ($(this).hasClass('selected')) {
// Allows a bag to be toggled when clicked
$(this).removeClass('selected');
} else {
// If there is no bag `selected` then make the clicked one selected
$(this).addClass('selected');
}
});
});
var check = setInterval(function() {
if ($('.bag.one').hasClass('selected')) {
$('.bag.one').droppable({
accept: '.item.one,.item.two,.item.three',
onDragEnter: function (e, source) {
$(source).draggable('options').cursor = 'auto';
},
onDragLeave: function (e, source) {
$(source).draggable('options').cursor = 'not-allowed';
},
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
addProduct(name, parseFloat(price.split('$')[1]));
}
});
} else if ($('.bag.two').hasClass('selected')) {
$('.bag.two').droppable({
accept: '.item.two,.item.three',
onDragEnter: function (e, source) {
$(source).draggable('options').cursor = 'auto';
},
onDragLeave: function (e, source) {
$(source).draggable('options').cursor = 'not-allowed';
},
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
}
});
} else if ($('.bag.three').hasClass('selected')) {
// Allow things to be dragged only to bag three
$('.bag.three').droppable({
accept: '.item.three',
onDragEnter: function (e, source) {
$(source).draggable('options').cursor = 'auto';
},
onDragLeave: function (e, source) {
$(source).draggable('options').cursor = 'not-allowed';
},
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
}
});
}
}, 100);
function addProduct(name, price) {
var totalQuantity = sumQuantity(data);
if (totalQuantity < 8) {
function add() {
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
row.quantity += 1;
return;
}
}
data.total += 1;
data.rows.push({
name: name,
quantity: 1,
price: price,
remove: '<a href="#" class="remove" onclick="removeProduct(this, event)">X</a>'
});
}
add();
totalCost += price;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
} else {
alert('cannot have more than 8 items');
}
}
function removeProduct(el, event) {
var tr = $(el).closest('tr');
var name = tr.find('td[field=name]').text();
var price = tr.find('td[field=price]').text();
var quantity = tr.find('td[field=quantity]').text();
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
data.rows.splice(i, 1);
data.total--;
break;
}
}
totalCost -= price * quantity;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
}
function sumQuantity(data) {
var sum = 0;
for (var i = 0; i < data.total; i++) {
sum += data.rows[i].quantity;
}
return sum;
}
Он по-прежнему должно быть исправлено в том, что вы должны отключить другие, используя что-то вроде $(this).droppable("option", "disabled", true);
и повторно включить его, когда он selected
, а также дело с мешками два и три, но это дает вам гораздо больше работать с
Быстрый вопрос: у вас будет несколько тележек для других сумок? Я не совсем уверен, почему у вас есть три сумки ...
Примите Aways для вас ... (надеюсь):
- УЗНАТЬ КАК КОД ONLINE. Это позволит решать проблемы, оптимизировать и просто делать все гораздо лучше. Используйте обучающие веб-сайты, такие как CodeAcademy, чтобы узнать больше. Вы NEED a основы в кодировании веб-кода в сети
- Попробуйте повторно использовать код, в котором вы можете. Если у вас будет более одного элемента того же типа, который имеет очень похожие характеристики, попробуйте использовать класс в отличие от жесткого кодирования каждого из них - это цель класса
- Попробуйте сами прежде чем спрашивать других. Когда вы задали вопрос, вы указали нулевые доказательства, что вы пытались сделать это сами. Вы должны работать над проблемой в течение нескольких дней, прежде чем задавать вопрос здесь, если только вы не являетесь . 100% уверены, что вы не собираетесь его получать.
- Сохраните свой код. Правильно используйте интервалы и убедитесь, что все ваши
()
и {}
выстраиваются в линию. Вы преуспели в том, чтобы называть ваши переменные узнаваемыми вещами, так что это хорошо
- Проверьте свой код на наличие ошибок. Просматривая это, я обнаружил несколько недостающих
</div>
с, опечатки, недостающие </li>
и другие ошибки, которые можно легко устранить. Это просто небрежность
- Стиль ваших элементов с помощью панели CSS в jsFiddle или в тегах
<style>
на веб-страницах. Это значительно облегчает просмотр того, что влияет на что. Встраивание в линию следует избегать любой ценой
- Научитесь использовать контролер элементов вашего браузера и консольный журнал. Это затрудняет исправление некоторых проблем и помогает вам точно увидеть элементы стилей во время работы среди многих других вещей.
Это сообщение прошло слишком долго, но я надеюсь, что я помог. На самом деле вам нужно получить более прочную основу в знаниях javascript, HTML, CSS и jQuery, прежде чем продолжить работу. Это должно быть вашим главным приоритетом прямо сейчас.
В заключение (так как это чувствует, как письмо):
«Если отладка процесс удаления ошибок, то программирование должно быть процесс сдачи их.» - Эдсгер Дейкстр
Вы должны программируете много ^^
----- FINAL РЕД -----
Я действительно работал слишком трудно на это , Ты должен мне что-то.
Anywho, я перестроил все это снова, чтобы получить его полностью функциональным. Мне нужно было создать тип mini-version, чтобы убедиться, что мои понятия верны. Оказывается, у меня просто было несколько дополнительных областей данных в моем HTML ...
Единственное, что у меня нет, это кнопка удаления (X в таблице). У меня нет никакой земной идеи, почему это перестало работать, я triple проверил весь код, потому что он такой же, как и раньше.
Обновленный код:
/* HTML */
<div id="body">
<div class="bag one" data-scope="one, two, three">Bag 1
<img src="images/sb1.jpg" height="50" width="50" />
</div>
<div class="bag two" data-scope="two, three">Bag 2
<img src="images/sb2.jpg" height="50" width="50" />
</div>
<div class="bag three" data-scope="three">Bag 3
<img src="images/sb3.jpg" height="50" width="50" />
</div>
<div class="products" style="width: 120px; height: 100px; left: 23px; top: 120px;">
<ul>
<li> <a href="#" class="item one" data-scope="one">
<img src="images/shirt2.gif" height="45" width="45"/>
<div>
<p>item1_1</p>
<p>Price:$25</p>
</div>
</a>
</li>
</ul>
</div>
<br>
<div class="products" style="width: 120px; height: 100px; left: 30px; top: 225px;">
<ul>
<li> <a href="#" class="item two" data-scope="two">
<img src="images/shoes1.gif" height="45" width="45"/>
<div>
<p>item2_1</p>
<p>Price:$30</p>
</div>
</a>
</li>
</ul>
</div>
<div class="products" style="width: 120px; height: 144px; left: 34px; top: 342px;">
<ul>
<li> <a href="#" class="item three" data-scope="three">
<img src="images/shirt2.gif" height="45" width="45"/>
<div>
<p>item3_1</p>
<p>Price:$25</p>
</div>
</a>
</li>
</ul>
</div>
<br>
<div class="cart" style="left: 200px; top: 150px; height: 300px; width: 237px">
<div class="ctitle">Shopping Cart</div>
<div style="background:#fff">
<table id="cartcontent1" fitColumns="true" style="width1:300px;height:auto;">
<thead>
<tr>
<th field="name" width=140>Name</th>
<th field="quantity" width=60 align="right">Quantity</th>
<th field="price" width=60 align="right">Price</th>
<th field="remove" width=60 align="right">Remove</th>
</tr>
</thead>
</table>
</div>
<p class="total">Total: $0</p>
<div class="ctitle" style="position:absolute;bottom:10px"></div>
</div>
</div>
/* CSS */
.bag {
width:80px;
float:left;
text-align:center;
}
.products {
position:fixed;
height:100%;
background:#fafafa;
}
.products ul {
list-style:none;
margin:0;
padding:0px;
}
.products li {
display:inline;
float:left;
margin:10px;
}
.item {
display:block;
text-decoration:none;
}
.item img {
border:1px solid #333;
}
.item p {
margin:0;
font-weight:bold;
text-align:center;
color:#c3c3c3;
}
.cart {
position:absolute;
width:260px;
height:100%;
background:#ccc;
padding:0px 10px;
}
.ctitle {
text-align:center;
color:#555;
font-size:18px;
padding:10px;
}
.auto-style3 {
float: right;
position: relative;
width: 260px;
height: 100%;
background: #ccc;
padding: 0px 10px;
margin-bottom: 0px;
}
.selected {
background-color: #FFFF00;
}
/* javascript/jQuery */
$(document).ready(function() {
var data = {
"total": 0,
"rows": []
};
var totalCost = 0;
$('#cartcontent1').datagrid({
singleSelect: true
});
$('.item').each(function (index, div) {
var scope = $(this).attr('data-scope');
$(div).draggable({
revert: true,
proxy: 'clone',
onStartDrag: function() {
$('.bag:not(.bag[data-scope*=' + scope + '])').droppable('disable');
if($('.selected').length > 0)
$(':not(.selected)').droppable('disable');
$(this).draggable('options').cursor = 'not-allowed';
$(this).draggable('proxy').css('z-index', 10);
},
onStopDrag: function() {
$('.bag').droppable('enable');
$(this).draggable('options').cursor = 'move';
}
});
});
$('.bag').click(function() {
if ($('.selected').length > 0 && !$(this).hasClass('selected')) {
$('.selected').removeClass('selected');
$(this).addClass('selected');
} else if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
$(this).addClass('selected');
}
});
$('.bag').droppable({
onDrop: function (e, source) {
var name = $(source).find('p:eq(0)').html();
var price = $(source).find('p:eq(1)').html();
addProduct(name, parseFloat(price.split('$')[1]));
$(source.draggable).remove();
$('.bag').droppable('enable');
}
});
function addProduct(name, price) {
var totalQuantity = sumQuantity(data);
if (totalQuantity < 8) {
function add() {
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
row.quantity += 1;
return;
}
}
data.total += 1;
data.rows.push({
name: name,
quantity: 1,
price: price,
remove: '<a href="#" class="remove" onclick="removeProduct(this, event)">X</a>'
});
}
add();
totalCost += price;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
} else {
alert('cannot have more than 8 items');
}
}
function removeProduct(el, event) {
var tr = $(el).closest('tr');
var name = tr.find('td[field=name]').text();
var price = tr.find('td[field=price]').text();
var quantity = tr.find('td[field=quantity]').text();
for (var i = 0; i < data.total; i++) {
var row = data.rows[i];
if (row.name == name) {
data.rows.splice(i, 1);
data.total--;
break;
}
}
totalCost -= price * quantity;
$('#cartcontent1').datagrid('loadData', data);
$('div.cart .total').html('Total: $' + totalCost);
}
function sumQuantity(data) {
var sum = 0;
for (var i = 0; i < data.total; i++) {
sum += data.rows[i].quantity;
}
return sum;
}
});
Это все, что я собираюсь сделать для вас, это гораздо больше, чем вы заслуживаете тем более, что вы предоставили 0 помощь с момента размещения вопроса. Не ожидайте этого от кого-либо.
Here is the last Fiddle I'm touching. Хороший день
«Я пробовал все возможные пути» - очевидно, что вы этого не сделали, или он будет работать сейчас. Возможно, вы должны включить некоторые из возможных способов, которые вы пробовали. –
Я имею в виду поиск других дубликатов, и я очень новичок в jquery.If u может plz помочь мне. – Heybey
@Heybey Как вы хотите, чтобы пользователи «выбирали» сумку? Нажав на нее? Вам нужно быть более ясным –