方法:1、用“document.getelementsbytagname(\”title\”)[0].innertext=\’值\’”語句;2、用“document.title=\’值\’”語句;3、用“$(\’title\’).html(\’值\’)”語句。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5&&jquery1.10.2版、dell g3電腦。
js設(shè)置html title標(biāo)題
innertext 方式
通過console.log(document.getelementsbytagname(\”title\”)[0]),發(fā)現(xiàn)能打印出<title>標(biāo)簽,標(biāo)簽里面只有文字節(jié)點(diǎn),故猜測(cè)只能識(shí)別textnode,所以用innertext方式設(shè)置title的值,果然成功了。
document.getelementsbytagname(\”title\”)[0].innertext = \’需要設(shè)置的值\’;
document.title方式
經(jīng)過測(cè)試,還可通過document.title 設(shè)置title的值。
console.log(document.title); # 可以獲取title的值。document.title = \’需要設(shè)置的值\’; # 設(shè)置title的值。
jquery方式
jquery方式我們?cè)跒g覽器取得了焦點(diǎn)和失去焦點(diǎn)的時(shí)候改變title的值,可以發(fā)現(xiàn)切換瀏覽器選項(xiàng)卡的時(shí)候,title發(fā)生了改變。
當(dāng)然如果你的項(xiàng)目里面依賴jquery,可以使用jq的方法設(shè)置
$(\’title\’).html(\’需要設(shè)置的值\’)$(\’title\’).text(\’需要設(shè)置的值\’)
例:
<!doctype html><html><head><meta charset=\”utf-8\”><title>hello</title><script src=\”js/jquery-1.7.2.min.js\”></script></head><body><script type=\”text/javascript\”>// $(\’title\’).html(\’php中文網(wǎng)\’);$(\’title\’).text(\’php中文網(wǎng)\’);</script></body></html>
總結(jié)
原生js中我們可以通過innertext,document.title兩種方式動(dòng)態(tài)修改網(wǎng)頁的title .
jq中我們可以通過$(\’title\’).html(\’\’)或者$(\’title\’).text(\’\’)進(jìn)行修改。
【推薦學(xué)習(xí):javascript高級(jí)教程】