0

我猜我所拥有的有点不寻常。我有这个deleteItem在点击时触发的功能,并具有以下参数

function dItem(type,id,element,confirmed){
    if(confirmed){
        handle delete function
    }else{
        var c = ',';
        popup('Are you sure you want to delete this item?',
            {
                "Yes":"dItem('"+type+"'"+c+id+c+element+c+true+")",
                "Cancel":"popupClose()"
            }
        )
    }
}

.. onclick='dItem("comment",15,this,false)' ..

popup()的第二个参数中传递了要在弹出窗口中显示的按钮以及它们分别调用的函数。问题是那element是一个HTMLDIV element,我想不出一种巧妙的方法来通过一个字符串传递它。我能想到的唯一解决方案是有一个全局变量来保存有问题的元素并且根本不传递它,尽管我真的不想这样做,因为它更像是一种破解而不是解决方案。有谁知道我如何通过字符串传递该元素?提前致谢!

编辑

这就是按钮对象b被处理并转换为HTML. 你知道我如何为它提供一个实际的函数,而不仅仅是一个字符串形式的名称吗?

var _b = '';
for(var i in b){
    _b+="<div onclick='"+b[i]+"'>"+i+"</div>";
}
4

1 回答 1

2

使用回调处理这种情况更为常见。您需要更改弹出功能才能使其正常工作。

例子:

popup('Are you sure you want to delete this item?', {
    "Yes": function () {
        dItem(type, id, element, confirmed);
    },

    "Cancel": function () {
        popupClose();
    }
});

作为一种解决方法,您可以简单地为元素生成一个唯一 ID,并在以后使用它来标识该元素。element因为您的函数是递归的,所以您需要处理可以是 aELEMENT_NODE或 a的事实string

for(var i in b){
    var generatedId = i /* TODO: not sure this generates an unique id */;
    _b += "<div id='" + generatedId + "' onclick='" + b[i] + "'>" + i + "</div>";
}

function dItem (type, id, element, confirmed) {
    if (confirmed) {
        // handle delete function
    }else{
        var elementId;

        // find the elementId
        if (element && element.nodeType && element.nodeType == 1) {
            elementId = element.id;
        }else if (typeof element == 'string') {
            elementId = element
        }else{
            throw Error('Argument [element] is not a ELEMENT_NODE or string');
        }

        var args = [type, id, elementId, true];

        popup('Are you sure you want to delete this item?', {
            "Yes": "dItem(" + args.join(', ') + ")",
            "Cancel": "popupClose()"
        });
    }
}
于 2013-08-25T14:48:13.440 回答