2015-01-09 60 views
0

我試圖訪問嵌套在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屬性的值。 –

回答

1

您的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

0

有人打翻我關閉以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