如何访问嵌套在h1标签中的img标签元素

问题描述:

我试图访问嵌套在h1元素中的img元素,以便我可以更改图像的源属性。但是,我似乎无法得到firstChild,nextSibling或nextElementSibling的正确组合。如何访问嵌套在h1标签中的img标签元素

**注:**我使用的平台只允许内联样式和脚本。我不能把功能放在头上。脚本标记被忽略。

我想单击h1元素时替换图像源。这里是我的代码:

<div> 
    <h1 onclick="(function() 
    { 
    if(this.nextElementSibling.style.display !== 'none'){ 
    this.nextElementSibling.style.display = 'none'; 
    this.innerHTML = '&nbsp;Click'; 
    console.log(this.nextElementSibling.nodeName); 
    console.log(this.firstChild.nodeName); 
    }else{ 
    this.nextElementSibling.style.display = 'block'; 
    this.innerHTML = '&nbsp;Click'; 
    console.log(this.firstChild.nodeValue); 
    } 
    }).call(this);">&nbsp;<img src="r_arrow.png" />Click</h1> 

    <div style="display:none; border:solid 1px red;"> 
    Some hidden content 
    </div> 
</div> 

我用的console.log,但我仍然无法弄清楚如何获得该img标签。

+0

WAT?什么样的平台力量在HTML属性值中评估JS。这很重要。 – Sukima

+0

这是代码以前工作的方式剩下的。大部分形式,您的解决方案工作。我只需要添加setAttribute()方法来更改src属性的值。 –

您的img元素是h1的唯一子元素,但是当您使用this.firstChild时,您可能会回到对包含&nbsp;的文本节点的引用。要选择一个实际的元素,你有几种选择,包括:

this.querySelector("img").src = "whatever"; 
this.getElementsByTagName("img")[0].src = "whatever"; 

另外,我注意到你的代码,包括行:

this.innerHTML = '&nbsp;Click'; 

这将覆盖h1元素的现有内容,取而代之的是该文本,即它将删除img元素。鉴于你的if/else的两个分支都将.innerHTML设置为相同的字符串,我不认为你需要这样做。

这是你的代码的工作版本:

<h1 onclick="(function() 
{ 
var next = this.nextElementSibling, 
    img = this.querySelector('img'); 
if(next.style.display !== 'none'){ 
    next.style.display = 'none'; 
    img.src = 'r_arrow.png'; 
}else{ 
    next.style.display = 'block'; 
    img.src = 'some_other_arrow.png'; 
} 
}).call(this);">&nbsp;<img src="r_arrow.png" />Click</h1> 

演示:http://jsbin.com/kubufexabu/1/edit?html,output

+0

我的解决方案奏效,但你的方式更好。谢谢 –

+0

不客气。除了我引入了一些变量以避免重复'this.nextElementSibling'和'this.querySelector' - 当然这不是*必须的,但是它使得它更易于阅读,除此之外,我的基本上和你的一样... – nnnnnn

+0

P.S.请注意,IE7不支持'.querySelector()',所以如果您确实需要支持IE7,请改用'this.getElementsByTagName(“img”)[0]'。 – nnnnnn

有人打翻我关闭以querySelector。我的代码现在做它需要做的事情。

我的最终代码:

<div> 
    <h1 onclick="(function() 
    { 
    if(this.nextElementSibling.style.display !== 'none'){ 
    this.nextElementSibling.style.display = 'none'; 
    this.querySelector('img').setAttribute('src','r_arrow.png'); 
    console.log(this.nextElementSibling.nodeName); 
    console.log(this.firstChild.nodeName); 
    }else{ 
    this.nextElementSibling.style.display = 'block'; 
    this.querySelector('img').setAttribute('src','d_arrow.png'); 
    } 
    }).call(this);">&nbsp;<img src="r_arrow.png" />Click</h1> 

    <div style="display:none; border:solid 1px red;"> 
    Some hidden content 
    </div> 
</div> 

+0

有人吗?那是我,但我删除了我的评论,并将其作为答案。请注意,你不需要'.setAttribute()'来设置'src',你可以说'.src =“something”;' – nnnnnn