2014-09-12 76 views
0

我遇到了JavaScript问题。 我想要发生的事情:单击“修改HTML内容”后,将“原始内容”h1更改为“新内容”,再次单击时,“新内容”更改为“原始内容”。当点击“删除HTML内容”按钮时,h1标题消失,再次单击时,空白更改为“原始内容”。相反,没有任何反应。 h1标题保持不变。有人可以帮忙吗?使用按钮更改标题

HTML:

<html> 
<head> 
<title>Content Change</title> 
<script type="text/javascript" src="contentchange.js"></script> 
</head> 
<body> 
<h1 id="heading"><b>The Original Content</b></h1> 
<br/> 
<button type="button" onclick="change()" id="button_one">Modify HTML content</button> 
<button type="button" onclick="change_2()" id="button_two">Delete HTML content</button> 
</body> 
</html> 

的JavaScript:

//Code for the Modify HTML content button 
function change() 
{ 
var elem = document.getElementById("button_one"); 

if (h1.value=="The Original Content") 
{h1.value = "The New Content";} 
else 
{h1.value = "The Original Content";} 
} 

//Code for the Delete HTML content button 
function change_2() 
{ 
var elemtwo = document.getElementById("button_two"); 

if (h1.value=="The Original Content" || "The New Content") 
{h1.value = "";} 
else 
{h1.value="The Original Content"} 
} 
+0

变量'h1'定义在哪里? – Regent 2014-09-12 21:21:08

+0

当定义了h1时(参见上面的Regent)将if(h1.value ==“原始内容”||“新内容”)行改为if(h1.value ==“The Original Content “|| h1.value ==”新内容“)' – 2014-09-12 21:25:43

回答

1

您可能需要设置h1变量,如下所示:

var h1 = document.getElementById('heading'); 

然后使用innerHTML代替value去改变它。

此外,你需要检查的b标签,就像这样:

if (h1.innerHTML === "<b>The Original Content</b>" || 
    h1.innerHTML === "<b>The New Content</b>" 
    ) 

小提琴:http://jsfiddle.net/Ls5osy22/2/

0

你需要做一个改变HTML如更换

<h1 id="heading"><b>The Original Content</b></h1> 

With

<h1 ><b id="heading">The Original Content</b></h1> 

::更改JavaScript代码::

function change(){ 
    var elem = document.getElementById("heading"); 
    if (elem.innerHTML=="The Original Content"){ 
     elem.innerHTML = "The New Content"; 
    } 
    else{ 
     elem.innerHTML = "The Original Content"; 
    } 
} 

function change_2(){ 
    var elem = document.getElementById("heading"); 
    if (elem.innerHTML=="The Original Content" || elem.innerHTML=="The New Content"){ 
     elem.innerHTML = ""; 
    } 
    else{ 
     elem.innerHTML="The Original Content" 
    } 
} 
0

...如果你somewhy不想既不使用也不h1.innerHTML === "<b>The Original Content</b>"<h1 ><b id="heading">The Original Content</b></h1>,您可以使用.textContent

Fiddle

function change() 
{ 
    var h1 = document.getElementById("heading"); 
    if (h1.textContent == "The Original Content") 
    { 
     h1.textContent = "The New Content"; 
    } 
    else 
    { 
     h1.textContent = "The Original Content"; 
    } 
} 

function change_2() 
{ 
    var h1 = document.getElementById("heading"); 
    if (h1.textContent == "The Original Content" || h1.textContent == "The New Content") 
    { 
     h1.textContent = ""; 
    } 
    else 
    { 
     h1.textContent = "The Original Content"; 
    } 
} 

而只是为了完整性fiddle它怎么会与有关标签的jQuery提及。