2016-05-28 51 views
0

的内容比如我要改变,像这样的HTML:试图换一个段落的标题属性与段落

<p title="Title text">Content text</p> 

成这样:

<p title="Content text">Title text</p> 

到目前为止,我此代码将使title值等于什么是<p>

window.addEventListener("load",init); 

function init(){ 

var b = document.querySelector("p"); 
b.setAttribute("title",b.textContent); 

console.log(b); 
} 
+1

当然,你需要覆盖它之前检索当前标题。因此,使用'getAttribute()'并将其存储到一个临时变量中,并在该属性设置后使用该变量来设置'.textContent'。 –

回答

0

瑞士法郎AP使用它们持有的值的变量,同时更新

window.addEventListener("load", init); 
 

 
function init() { 
 
    var b = document.querySelector("p"); 
 
    var temp = b.textContent; 
 
    b.textContent = b.getAttribute("title"); 
 
    b.setAttribute("title", temp); 
 
    console.log(b); 
 
}
<p title="Title text">Content text</p>