我将如何替换 ajax 加载的 html 文档上的元标题、关键字和描述



如何将文档上的元标题和描述替换为 ajax 调用中传入 html 文档中的元标题和描述?

我正在从相邻 html 文档上的 #contentdiv 调用新内容。我想发生的是,当新内容加载时,我想替换主要文档标题(以及描述和关键字...还不如因为无论如何我在那里使用工具)在正在加载的 HTML 文件中使用元标题。

我考虑过使用 replace(); 或 match(); 但我只是想找出最好的方法。

这是脚本:

// JavaScript Document
$(document).ready(function() {
    var toLoad
    $(window).bind( "hashchange", function(e) {
            loadcontent();
            return false;
    });

        $('#toc li a').click(function(){
            window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-0);
            var href = $(this).attr( "href" );
            $('meta[name=title]').attr('title', new_title);
            $('meta[name=description]').attr('description', new_description);
            $('meta[name=keywords]').attr('keywords', new_keywords);
            //alert("hey" + window.location.hash);
            $('#breadcrumbs h1').append(" </a><a href='index.html"+ window.location.hash + "' >" + $(this).attr('href') +" ></a>");
            $.bbq.pushState({ url: href });
            $(window).trigger( "hashchange" );
        });
    loadcontent();
});
function loadcontent(){
    var toLoad = window.location.hash.replace("#","") +'.html #content';
            $('#content').hide('slow');
            $('#load').remove();
            $('#conContainer').append('<span id="load">LOADING...</span>');
            $('#load').fadeIn('normal');
            $('#content').load(toLoad,'',function(returnText,status,request){
                showNewContent()
            });
            function loadContent() {
                $('#content').load(toLoad,'',showNewContent());
            }
            function showNewContent() {
                $('#content').show('slow',hideLoader());
            }
            function hideLoader() {
                $('#load').fadeOut('normal');
            }
}

对于标题,您可以执行以下操作:

$('title').html('my new meta title');

给你的元描述和关键词元素一个id,这样你就可以轻松选择元素了:

$('#mdescription').attr('content', 'my new meta description');
$('#mdkeywords').attr('content', 'keyword one, keyword two');

最新更新