关于jquery和lodash,没人知道吗?
发布于 9 年前 作者 hanyuzhou2006 4825 次浏览 最后一次编辑是 8 年前 来自 问答

index.html

<select id="name"></select>
<select id="type"></select>
<select id="value"></select>
<script src="jquery-1.12.3.min.js"></script>
<!--<script src="lodash.js"></script>-->
<script src="app.js"></script>

app.js

var _;
var lodashSupport = true;
if (_ == undefined) {
    lodashSupport = false;
    _ = {
        groupBy: function(arr, property) {
            var maps = {};
            for (var i = 0; i < arr.length; i++) {
                var prop = arr[i][property];
                if (maps[prop] == null) {
                    maps[prop] = [];
                }
                maps[prop].push(arr[i]);
            }
            return maps;
        }
    }
}
function renderDom(maps, $container) {
    $container.empty();
    for (var p in maps) {
        var $option = $('<option value="' + p + '">' + p + '</option>');
        $option.appendTo($container);
    }
}

function renderValue(arr, renderTree, index) {
    var property = renderTree[index];
    var maps = _.groupBy(arr, property);
    var $dom = $('#' + property);
    renderDom(maps, $dom);
    
    var callback = function() {
        renderValue(maps[$dom.val()], renderTree, next);
    }
    var next = index + 1;
    if (next >= renderTree.length) return;

    if (lodashSupport) {
        $dom.on('change', callback)
    } else {
        $dom[0].onchange = callback;
    }
    callback();
}

var tree = [
    "name", "type", "value"
]
var data = [
    { "name": "abc", "type": "1", "value": "haha1" },
    { "name": "abc", "type": "2", "value": "haha2" },
    { "name": "abc1", "type": "1", "value": "haha2" },
    { "name": "abc1", "type": "3", "value": "haha3" },
    { "name": "abc2", "type": "2", "value": "haha3" },
    { "name": "abc2", "type": "3", "value": "haha3" },
    { "name": "abc2", "type": "4", "value": "haha4" },
    { "name": "abc3", "type": "1", "value": "haha4" },
    { "name": "abc3", "type": "2", "value": "haha5" },
    { "name": "abc3", "type": "3", "value": "haha5" },
    { "name": "abc3", "type": "2", "value": "haha6" },
    { "name": "abc4", "type": "5", "value": "haha6" }
]
renderValue(data, tree, 0);

以上代码实现功能为级联树,运行时没有问题。
问题在于: 当我使用lodash的时候,可以用jquery事件,但当我不使用lodash的时候,用jquery事件就会出错,只能用原生事件。 真心求教。

回到顶部