簡體   English   中英

從上下文中獲取標題

[英]get the title from a context

如何選擇上下文標題? 我想選擇它來更改頁面標題。

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

編輯 :我忘記了doctype,以防萬一是必要的。 上下文來自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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM