【问题标题】:How to pass div id, class as parameters to a function called by an anchor tag onclick?如何将 div id、类作为参数传递给锚标记 onclick 调用的函数?
【发布时间】:2015-05-20 12:57:47
【问题描述】:

我正在尝试将 table id、div id 和嵌套类名传递到一个在整个程序代码中使用的通用函数中。

棘手的部分是,该函数调用另一个函数,该函数被包装在锚标记的 onclick 事件中。在添加两个附加参数之前,函数removeItem 工作并且现在不再触发。为了使函数可重用,这两个参数是必需的。

expected programme.的jsfiddle

两个 id(参数)都作为带引号的字符串传递,

var tableid = "'#tble1200'"
var otherid = "'div.class1 .total'"

function AddProduct(elment, event, tableid, otherid)
{
   //do something
   //the hyperlink is remove
   remove: '<a href="#" class="remove" 
   onclick="removeProduct(this, event,tableid,otherid)">X</a>'
}

function removeProduct(element, event, tblid, othid)
{
    //do something
    $(tblid).datagrid('loadData', data);
    $(othid).html('Total: $'+subTotal);
}

我正在尝试来自 this post's jsfiddle here. 的代码:原始代码。

function addProduct(name,price){
        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;
        $('#cartcontent').datagrid('loadData', data);
        $('div.cart .total').html('Total: $'+totalCost);
    }

【问题讨论】:

  • 你能告诉我们这些函数是如何使用的吗?将 JS 代码作为字符串传递不是您想要做的事情 - 它可以工作,但您不能真正按照您想要的方式绑定范围。
  • @Halcyon 我有一个例子using here. 不是有一个购物车,而是有多个购物车。而且我不想有重复的 addProduct 和 RemoveProduct 函数。相反,我想为所有购物车重用这两个功能。这就是为什么我使用一种方法来参数化底层元素 id
  • 我并不关心removeItem 函数,我感兴趣的是main 函数。你如何使用这个函数?
  • @Halcyon 我更新了我的帖子。如果 JS 代码不作为字符串传递,我这里还有什么选择?
  • 能否请您发布一个不起作用的代码?

标签: javascript jquery html css anchor


【解决方案1】:

要让多个购物车独立工作,您必须将购物车数据存储在 arrayindex 中。并将index 传递给addProductremoveProduct functions。对于购物车内容,请使用 class 而不是 id

更新代码如下:

HTML

<!doctype html>
<html>
    <head>
        <title>Multiple Carts</title>
        <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
        <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
        <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
    </head>
    <body style="margin:0;padding:0;height:100%;background:#fafafa;">
        <ul class="products">
            <li>
                <a href="#" class="item">
                    <img src="images/shirt1.gif"/>
                    <div>
                        <p>Balloon</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
            <li>
                <a href="#" class="item">
                    <img src="images/shirt2.gif"/>
                    <div>
                        <p>Feeling</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
            <li>
                <a href="#" class="item">
                    <img src="images/shirt3.gif"/>
                    <div>
                        <p>Elephant</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
            <li>
                <a href="#" class="item">
                    <img src="images/shirt4.gif"/>
                    <div>
                        <p>Stamps</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
            <li>
                <a href="#" class="item">
                    <img src="images/shirt5.gif"/>
                    <div>
                        <p>Monogram</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
            <li>
                <a href="#" class="item">
                    <img src="images/shirt6.gif"/>
                    <div>
                        <p>Rolling</p>
                        <p>Price:$25</p>
                    </div>
                </a>
            </li>
        </ul>
        <div class="cart">
            <h1>Shopping Cart 1</h1>
            <div style="background:#fff">
                <table class="cartcontent" fitColumns="true" style="width: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>
            <h2>Drop here to add to cart</h2>
        </div>

        <div class="cart">
            <h1>Shopping Cart 2</h1>
            <div style="background:#fff">
                <table class="cartcontent" fitColumns="true" style="width: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>
            <h2>Drop here to add to cart</h2>
        </div>
    </body>
</html>

CSS

.products{
    list-style:none;
    margin-right:300px;
    padding:0px;
    height:100%;
}
.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:fixed;
    top: 0;
    right:0;
    width:300px;
    height:50%;
    background:#ccc;
    padding:0px 10px;
}
.cart:nth-child(odd){
    top:50% !important;
}
h1{
    text-align:center;
    color:#555;
}
h2{
    position:absolute;
    font-size:16px;
    left:10px;
    bottom:20px;
    color:#555;
}
.total{
    margin:0;
    text-align:right;
    padding-right:20px;
}

JS

var data = [];

$(function () {
    $('.cartcontent').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';
        }
    });
    $('.cart').droppable({
        onDragEnter: function (e, source) {
            $(source).draggable('options').cursor = 'auto';
        },
        onDragLeave: function (e, source) {
            $(source).draggable('options').cursor = 'not-allowed';
        },
        onDrop: function (e, source) {
            var $source = $(source);
            var name = $source.find('p:eq(0)').text();
            var price = $source.find('p:eq(1)').text();
            addProduct($('.cart').index($(e.currentTarget)), name, parseFloat(price.split('$')[1]));
        }
    });
});

function loadData(cartIndex, event) {
    var $cart = $('.cart:eq(' + cartIndex + ')');
    $cart.find('.cartcontent').datagrid('loadData', data[cartIndex]);
    $cart.find('.total').text('Total: $' + data[cartIndex].total);
}

function addProduct(cartIndex, name, price) {
    function add() {
        if (!data[cartIndex]) {
            data[cartIndex] = {
                length: 0,
                total: 0,
                rows: []
            };
        }
        for (var i=0; i < data[cartIndex].length; i++) {
            var row = data[cartIndex].rows[i];
            if (row.name === name) {
                row.quantity += 1;
                return;
            }
        }
        data[cartIndex].length++;
        data[cartIndex].rows.push({
            name: name,
            quantity: 1,
            price: price,
            remove: '<a href="#" class="remove" onclick="removeProduct(' + cartIndex + ', this)">X</a>'
        });
    }
    add();
    data[cartIndex].total += price;
    loadData(cartIndex);
}

function removeProduct(cartIndex, el) {
    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[cartIndex].length; i++){
        var row = data[cartIndex].rows[i];
        if (row.name == name) {
            data[cartIndex].rows.splice(i, 1);
            data[cartIndex].length--;
            break;
        }
    }
    data[cartIndex].total -=  price * quantity;
    loadData(cartIndex);
}

JS Fiddle

【讨论】:

  • And for cart content use class instead of id :它对功能有何影响?您的方法不会受到 jquery 范围问题的影响,因为您使用数组来存储,而不仅仅是像下面的答案那样的唯一索引?你能解释一下吗?这已经是一个很棒的解决方案了。
  • 因为您不能在同一个document 上对多个elements 使用相同的id,但您可以对多个elements 使用相同的class。否则$cart.find('.cartcontent').datagrid('loadData', data[cartIndex]); 将不起作用,您必须处理多个id 并加载相关的datagrid
  • @Manjoj 我设法找到了get it solved,并在途中学到了相当不错的东西。非常感谢你给我第一个方向和这段代码。虽然这对我来说只是一个学习代码,但它可以帮助很多。我一路被反对票打了一巴掌,有些人甚至来这里反对票;)
【解决方案2】:

functoin AddProduct(elment, event, tableid, otherid)

functoin拼写错误,应该是function

【讨论】:

    【解决方案3】:

    这是一个可行的解决方案:

    remove: '<a href="#" id="item-' + unique_nr + '" class="remove">X</a>'
    
    // later
    
    $("#item-" + unique_nr).click(function (event) {
        removeProduct(this, event, table_id, cart_id);
    });
    

    使用id,您可以稍后获取项目并绑定范围侦听器。

    见:http://jsfiddle.net/Vwu37/135/

    现在我正在传递table_idcart_id,您可以考虑传递实际的桌子和购物车,即。 $("#cartcontent")$(".cart")

    请记住,".cart" 不是唯一的,因此如果您想拥有两个列表,则需要使其唯一。

    【讨论】:

    • 您能否解释一下Using the id you can fetch the item later and bind a scope listener.$("#item-" + unique_nr).click 的关系?这远远超出了我目前的理解。 unique_nr 是如何工作的?
    • 还有一个slight problem with the data array. 它由两个购物车更新。所以我可能也必须将它作为参数传递。我想知道我是否必须为两个购物车提供 2 个重复的功能?有什么方法可以重用实现拖放的相同功能?
    • 那太好了。我不确定您是否尝试过同时向两个购物车添加一些物品。删除似乎不起作用并停留在一个项目上...可能导致此问题的原因是什么?
    • 我认为数据网格总是重新渲染节点,所以事件监听器消失了。这行得通:jsfiddle.net/Vwu37/140 你在这里看到的是你遇到了 jQuery 的限制。你会得到所有这些奇怪的错误,因为 jQuery 无法正确地进行范围界定。
    • 如果整个事情都可以在 javaScript 中完成,我就不必使用 jQuery,真的。事实上,这个当前的程序正在使用外部 UI,这不符合我的最大利益。您能否建议这种拖放是否可以在 JavaScript 中以类似的方式实现?我的数据库后端是在 Asp.Net(经典,而不是 MVC)中处理的。如果那是肯定的,那么这就是我从你那里学到的东西:)
    猜你喜欢
    • 1970-01-01
    • 2012-06-09
    • 2016-03-19
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    相关资源
    最近更新 更多