简体   繁体   English

从上下文中获取标题

[英]get the title from a context

How Do I select the title of the context? 如何选择上下文标题? I am suppose to select it to change the title of the page. 我想选择它来更改页面标题。

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

EDIT : I forgot the doctype just incase it's necessary. 编辑 :我忘记了doctype,以防万一是必要的。 The context was from an AJAX Request. 上下文来自AJAX请求。

You can use regex to extract the title as well 您也可以使用正则表达式提取标题

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

Demo 演示版


Just discovered a way to do this, the non-regex way 刚刚发现了一种执行此操作的方法,即非正则表达式

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

Demo 演示版

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/MdvWq/

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

$(context)[1].innerHTML

returns the title 返回标题

I don't know why, but nobody mention this. 我不知道为什么,但是没有人提及。 This is a popular method to search for elements in responses: 这是一种在响应中搜索元素的流行方法

$(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/ http://jsfiddle.net/DerekL/THdaC/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM