javascript - DOM/页面未更新,但 console.log 显示更新值

标签 javascript jquery html

我正在从头开始做 SPA,到目前为止,除了导航链接的 active 状态不会根据用户导航到的位置进行更新之外,一切正常。

有趣的是,当我在 Chrome 中打开开发人员工具时,在“Elements”下,DOM 仍然在原始导航元素上显示 active 类,但在“Console”下,当我console.log该元素,它显示该类已被删除。

我在一些地方尝试了 event.stopPropagation()jQuery.off() 函数,但似乎没有任何方法可以解决这个问题。

问题:单击导航链接时,事件链接和前一个事件链接的类列表不会更新,但 console.log 函数确实会显示前一个事件链接的更新后的类列表

期望的行为:前一个事件链接丢失其 active 类,并且当前事件链接在其导航链接之后获得 active 类已被单击,页面呈现新内容(所谓的新页面)。

更新1:根据建议更新了代码,它解决了我问题的第一部分。现在可以从所有 li 元素中删除 active 类,但在导航后使页面在当前事件链接上使用 active 类呈现更新后的链接则不起作用工作。请参阅 app.js 中的generateView() 函数。

更新 2: 成功了。请参阅此问题的底部。谢谢!

我的app.js

(function ($, hbs){

'use strict';

// declare some usefull variables to use throughout the app
var
    doc = document,
    oldPath = '',
    newPath = '',
    navParentEl = '';


// 1: Manually trigger a hashchange to start the app.
window.onload = function (e) {
    $(window).trigger('hashchange');
};

// 2: Catch clicks on the root-level element for anchor tag clicks.
doc.body.addEventListener('click', function (e) {
    //e.stopPropagation();
    var tag = e.target;

    // check element clicket
    if (tag.tagName === 'A' && tag.href && e.button === 0) {
        // it's a left-click on an anchor. Lets navigate!
        if (tag.origin === window.location.origin) {
            // prevent the page from navigating

            e.preventDefault();

            // it's a link within the site, HURRAY!
            oldPath = window.location;
            newPath = tag.href,
            navParentEl = tag.parentElement;

            console.log(navParentEl);

            // Update the URL bar! IMPORTANT!
            // @TODO: MOVE INTO A FUNCTION OR OBJECT
            window.history.pushState(null, '', newPath);
            render(window.location.hash, data, e);
        }
    }
});

// register Handlebars partials
hbs.registerPartial({
    'header': hbs.templates.header,
    'footer': hbs.templates.footer
});

$(window).on('hashchange', function (e) {
    // On every hash change the render function is called with the new hash.
    render(window.location.hash, data, e);
});

function render(url, data, evt) {
    var temp = url.split('/')[0];

    // Hide current page
    $('.pages').addClass('hidden');

    // remove anchors .active class
    //$('.nav-parent').removeClass('active');

    var map = {
        '': function (data) {
            renderPage('home', data);
        },
        '#home': function (data) {
            renderPage('home', data);
        },
        '#gallery': function (data) {
            renderPage('gallery', data);
        },
        '#about': function (data) {
            renderPage('about', data);
        }
    };

    if (map[temp]) {
        map[temp](data);
    } else {
        renderErrorPage(data);
    }
}

function renderPage(page, data) {
    var tpl = hbs.templates[page](data);
    generateView(tpl, page);
}

function renderErrorPage(data) {
    renderPage('error', data);
}

function generateView(tpl, page) {
    var pageId = '#' + page;

    $(pageId).removeClass('hidden');
    $('.container').html(tpl);

    // this works for removing the active class from all li elements
    $('.nav-parent').removeClass('active');

    // add .active class to the new active anchor element
    // does not work
    $(navParentEl).addClass('active');

}

})(jQuery, Handlebars);

我的导航 HTML:

<div class="header clearfix">
    <nav>
        <ul class="nav nav-pills pull-right">
            <li role="presentation" class="nav-parent active"><a href="#home" class="links">Home</a></li>
            <li role="presentation" class="nav-parent"><a href="#gallery" class="links">Gallery</a></li>
            <li role="presentation" class="nav-parent"><a href="#about" class="links">About</a></li>
            <li role="presentation" class="nav-parent"><a href="#contact" class="links">Contact</a></li>
        </ul>
    </nav>
    <h3 class="text-muted">{{ projectName }}</h3>
</div>

更新 2:经过一些提示后,它开始工作了。我需要重新考虑我的 generateView() 函数。这是该函数的最终代码:

function generateView(tpl, page) {
    var pageId = '#' + page;

    // remove hidden class from content to be shown
    $(pageId).removeClass('hidden');
    // add the template to the html
    $('.container').html(tpl);
    // move the active class from the former active link
    $('.nav-parent').removeClass('active');

    // get the current hash of the location
    var newHash = window.location.hash,
        // get all links
        _links = document.querySelectorAll('.links'),
        currentActiveLink = '';

    // iterate over the _links object and find the link with href === newHash
    for ( var i = 0; i < _links.length; i++ ) {
        if ( _links[i].getAttribute('href') === newHash ) {
            // store the link with href == newHash 
            // inside the currentActiveLink variable
            currentActiveLink = _links[i];
        }
    }

    // add active class to current active link
    currentActiveLink.parentElement.classList.add('active');
}

谢谢!

最佳答案

你有没有可能重画你的导航?并没有真正浏览你的代码,但我花了很长时间才在我的 SPI 中发现这一点。我更改了一些参数,但我还使用默认服务器端属性使用 ajax 加载了这些元素... 编辑:是的,我可以看到您的应用程序中发生了这种情况

关于javascript - DOM/页面未更新,但 console.log 显示更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977469/

相关文章:

javascript - Canvas 平移所有元素,包括小 map

javascript - 导入外部脚本时出现 404

html - Angular2 - 动态添加 HTML 属性和类

javascript - 函数不会停止运行 Angular 5

javascript - JSON.stringify 的反转?

jQuery 无法在 IE 7 和 Chrome 中工作

javascript - 如何取消由 jQuery 中的 ajaxSubmit() 启动的文件上传?

javascript - Bootstrap 3 轮播的问题

javascript - HTML 表单无法在移动设备上运行

html - @import 媒体查询 css 问题