📞 09318539889 📧 yxp@gansuwangzhan.cn

利用微信插件实现下拉列表

作者:杨锦龙时间:2026-01-09点击量:0次

前端

<form class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label"><img src="__YJZ__/images/1.png"/>所在省份</label>
        <div class="layui-input-inline">
            <!-- 点击触发选择器 -->
            <input type="hidden" name="relation_id" id="relation_id">
            <input type="text" data-relation-id=""  name="relation" lay-verify="relation" id="relation" placeholder="选择所在省份" readonly class="layui-input" style="background-color: #fff; cursor: pointer;">
        </div>
    </div>
</form>
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script src="https://res.wx.qq.com/t/wx_fed/weui.js/res/1.2.17/weui.min.js"></script>
<script>
    let cachedRelations = null;
    document.getElementById('relation').addEventListener('click', function () {
        const $input = this;
        // 如果已有缓存,直接弹出
        if (cachedRelations) {
            showPicker(cachedRelations, $input);
            return;
        }
        const loading = weui.loading('加载中...');
        fetch('/yejuzhi/Api/getTypeOne?model=11&pid=1')
            .then(res => res.json())
            .then(json => {
                loading.hide();
                if (json.code === 100 && Array.isArray(json.data)) {
                    cachedRelations = json.data
                        .filter(item => item.status === 1)
                        .sort((a, b) => a.sort - b.sort)
                        .map(item => ({ label: item.name, value: item.id }));

                    showPicker(cachedRelations, $input);
                } else {
                    weui.alert(json.msg || '加载失败');
                }
            })
            .catch(() => { loading.hide(); weui.alert('网络错误'); });
    });

    function showPicker(data, input) {
        weui.picker(data, {
            title: '选择省份',
            defaultValue: [3023],
            onConfirm: function (result) {
                input.value = result[0].label;
                //input.setAttribute('data-relation-id', result[0].value);
                document.getElementById('relation_id').value = result[0].value;
            }
        });
    }
</script>
<script>
    layui.use(['form','layer'], function() {
        $ = layui.jquery;
        var form = layui.form;
        let layer = layui.layer;
        form.render();
    });
</script>

后端程序

public function getTypeOne(){
    $model = Request::param('model');
    $pid = Request::param('pid');
    $where = array();
    $where[] = ['pid','=',$pid];
    $list = $this->DbSy->SelectList($model,'sort asc',$where);
    return json(['code' => 100, 'data' => $list]);
}

展示效果

企业微信截图_20260109110722.png