How would I replace the meta title, keywords and description on the ajax loaded html document?

回眸只為那壹抹淺笑 提交于 2019-12-22 06:51:15

问题


How would I replace the meta title and description on the document with the meta title and description from an incoming html document on an ajax call??

I am calling new content from the #content div on an adjacent html document. What I want to happen is when the new content loads I want to replace the main documents title (and description and keywords... might as well since im tooling around up there anyway) with the meta title in the html file that is being loaded.

I have thought about using replace(); or match(); but I just wanted to find out the best way.

here is the script:

// 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');
            }

}

回答1:


For the title you could do the following:

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

Give your meta description and keywords elements an id, so you can easily select the elements:

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


来源:https://stackoverflow.com/questions/10919456/how-would-i-replace-the-meta-title-keywords-and-description-on-the-ajax-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!