0

我对 jquery 很陌生。目前我正在做一个购物车项目,其中有三种类型的物品(item1,item2,item3)和三个袋子(bag1,bag2,bag3)和一个购物车,例如 bag1 接受 item1,item2,item3,bag2 接受item2、item3 和 bag3 仅接受我目前开发的 drop item3。

现在我想添加额外的功能,例如用户应该首先选择任何一个包(例如bag1),然后尝试将物品放入bag1,这样其他两个包丢弃功能应该被禁用(其他包甚至不应该接受任何物品如果该包可以接受)并且如果用户选择其他包也可以反转。

我尝试了所有可能的方法。任何人都请尝试一下。

http://jsfiddle.net/Vwu37/15/

html

<div class="bag1" ><p>bag1</p></div>
<div class="bag2" > <p>bag2</p></div>
<div class="bag3" ><p>bag3</p></div>
<div class="item1"><p>item1_1</p></div>
<div class="item1"><p>item2_1</p></div>
<div class="item1"><p>item2_1</p></div>   

js

 $('.bag1').droppable({
                accept: '.item1,.item2,.item3',
                 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]));
                }
            });

            $('.bag2').droppable({
                accept: '.item2,.item3',
                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();
                   }
            });

            $('.bag3').droppable({
                accept: '.item3',
                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();
                                    }
            });
4

1 回答 1

2

在您的位置上,我要做的不是拥有三个不同的类(,,,bag1bag2bag3而是创建一个名为的新类bag,并为每个袋子赋予该类,然后在另一个名为的类中指定特定于每个袋子的任何其他 CSS onetwo并且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');
    }
});

并为selected该类创建一些CSS,以便用户知道点击了哪一个

.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
 }

您的代码太大,我们无法为您实现整个事情。这应该为您提供正确的前进方向。如果还有什么我可以帮助您的,请发表评论

-----巨大的编辑-----

(我不应该这么努力地纠正你的情况,但我为你的立场感到难过,所以我做了)

在纠正代码格式、优化代码以供重用(并在此过程中删除数百行不需要的代码)、将我之前创建的 if 语句移动到 asetInterval以检查以使用当前信息更新它并更正之后你的很多糟糕的 CSS,我想出了这个粗略的更新

这是代码:

<!-- 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,并且还要处理袋子二和三,但这给了您更多的工作

快速提问:你会为其他包准备多个推车吗?我不太清楚你为什么有三个袋子......

为你带走......(希望):

  1. 了解如何在线编码。这将使解决问题、优化和简单地做所有事情变得更好。使用 CodeAcademy 等教程网站了解更多信息。您需要网络编码的基础才能在网络上编码
  2. 尽量重用代码。如果您要拥有多个具有非常相似特征的相同类型的元素,请尝试使用一个类,而不是对每个元素进行硬编码——这就是类的目的
  3. 在问别人之前自己尝试一下。当你问这个问题时,你提供了零证据表明你曾试图自己做。除非你100%确定你不会得到它
  4. 保持你的代码干净。正确使用间距并确保所有的(){}对齐。你在命名你的变量可识别的东西方面做得很好,这很好
  5. 检查您的代码是否有错误。翻阅它时,我发现了几个缺失</div>的 s、拼写错误、缺失</li>和其他可以轻松修复的错误。这只是粗心
  6. 使用 jsFiddle 中的 CSS 面板或<style>网页上的标签为您的元素设置样式。这使得更容易准确地看到是什么影响了什么。应不惜一切代价避免内嵌样式
  7. 学习使用浏览器的元素检查器和控制台日志。它使一些问题很容易解决,并帮助您准确了解元素在运行时具有哪些样式。

这篇文章现在已经发布得太久了,但我希望我有所帮助。确实,在继续工作之前,您确实需要在 javascript、HTML、CSS 和 jQuery 知识方面打下更坚实的基础。这应该是你现在的首要任务。

最后(因为这感觉像是一封信):

“如果调试是消除错误的过程,那么编程一定是把它们放进去的过程。” - Edsger Dijkstra

你一定已经编程了很多^^

-----最终编辑-----

在这方面我真的太努力了。你欠我一些东西。

无论如何,我再次重组了整个东西以使其完全发挥作用。我必须创建一种迷你版本来确保我的概念是正确的。事实证明,我的 HTML 中只是有几个额外的数据范围......

我唯一没有工作的是删除按钮(表中的 X)。我不知道为什么它会停止工作,我三次检查了所有代码,因为它和以前一样。

更新代码:

/* 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 次帮助。不要对任何人抱有这么大的期望。

这是我触摸的最后一个小提琴。祝你有美好的一天

于 2013-07-31T17:58:06.167 回答