从上下文中获取标题

get the title from a context

本文关键字:标题 获取 上下文      更新时间:2023-09-26

如何选择上下文的标题?我想选择它来更改页面的标题。

var handler = function(context){
    document.title = //context's title
    ....
}
//sample context from ajax request
var context = '<!DOCTYPE html><html>'
            <head><title>Hello</title></head>'
            <body>'
            <a href="#">Click Here</a><p>This is my sentence.</p>'
            </body></html>';
.ajax{(
    ...
    success: function(data){
                 handler(data);
             }
});

编辑:我忘记了文档类型,以防万一。上下文来自 AJAX 请求。

您也可以使用正则表达式来提取标题

var matches = context.match(/<title>(.*?)<'/title>/);
var title = matches[1];

演示


刚刚发现了一种方法,非正则表达式方式

title = $(context).filter("title");
console.log(title.html());

演示

jquery $ 函数的第二个参数是上下文所以你可以试试$("title",$(context)).text()

这应该可以:

var title = $(context).eq(0).text()
var handler = function(context){
    $xml=$.parseXML(context);
   console.log($($xml).find('title').text());
}

var context = '<html><head><title>Hello</title></head><body><a href="#">Click Here</a><p>This is my sentence.</p></body></html>';
    handler(context);

http://jsfiddle.net/MdvWq/

请检查 http://jsfiddle.net/sethunath/UAt5p/

$(context)[1].innerHTML

返回标题

我不知道

为什么,但没有人提到这一点。这是在响应中搜索元素的常用方法:

$(function() {
    var context = '<html><head><title>Hello</title></head><body><a href="#">Click Here</a><p>This is my sentence.</p>< /body></html > ';
    alert($(context).filter("title").html());   //Use filter to get elements you want
    alert($(context).filter("a").html());       //Will get HTML of that link (<a>)
    alert($(context).filter("body > p").html());  //HTML of <p>
});​

http://jsfiddle.net/DerekL/THdaC/2/