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

标签 jquery ajax replace title meta-tags

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

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

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

这是脚本:

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

关于jquery - 如何替换 ajax 加载的 html 文档上的元标题、关键字和描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10919456/

相关文章:

javascript - 如何中止ajax请求

javascript - 图像未使用 PHP 脚本保存

javascript - jQuery .post 或 .get 传递动态参数

javascript - 将外部 JSON URL 标签和值拉入新数组

javascript - 监听 Javascript 对象值的变化

jquery - .prop disable 在 Chrome 和 Firefox 中不起作用

javascript - jQuery $.ajax 调用——奇怪的返回函数问题

search - 在 vim 中获取最后一次搜索或搜索&替换字符串?

javascript - 将一个数组中的所有符号替换为另一个 JS 中的互补符号

c - 为什么这个字符替换程序不起作用?