HTML 下拉菜单的重定向(使用 JS)在移动设备上不工作,但在 PC 上工作正常

HTML Dropdown's redirection(using JS) not working on mobile, but works fine on PC

我的页面上有一个下拉菜单:

<div class="dropdown" data-method="redirect">
    <select id="weekselect">
        <option>Select a week</option>

        <option value="http://sample.com/page1/action">This Week</option>

    </select>
</div>

选择 an 后,它将被重定向到页面 http://sample.com/page1/action。它在 PC 上工作正常,但是当在移动设备上查看该站点时,重定向不起作用,它只是重定向到一个页面 undefined.

做重定向的JS代码是:

$(window).load(function (event) {

    $(document).on('click','#menu-bars', function (event) {
        $('body').toggleClass('nav-collapsed');
        $.scrollTo(0, 'fast');
    });

    var selectList = $('select');

    if( !$('html').is('.touch') ){
        selectList.select2({
            minimumResultsForSearch: -1
        });
    }

    selectList.on("change", function (e) {
        var parent = $(this).parents('.dropdown');
        var method = parent.data('method');


        if (method == 'redirect') {
            window.location = e.val;
        }

可能是在移动设备上查看网站时,window.location = e.val; 没有任何价值。

重定向页面时js不工作可能是什么原因?

不要使用 e.val,请尝试使用 $(this).val();

也使用 window.location.href

重定向

你需要改变

if (method == 'redirect') {
            window.location = e.val;
        }

if (method == 'redirect') {
            window.location = $(this).val();
        }

e 不是调用对象,它是事件对象。参见 the docs


真的,您应该将方法更改为:

selectList.on("change", function (e) {
        var caller = $(this);
        var parent = caller.parents('.dropdown');
        var method = parent.data('method');


        if (method == 'redirect') {
            window.location = caller.val();
        }

节省对 $(this) 的多次调用效率更高。


parents() 可以 return 多个对象,特别是如果您使用 class 选择器,那么您在该区域的代码不是很健壮。如果你期望倍数,你应该处理它(也许使用 each()), if you don't use parent() 而不是