2013-07-21 68 views
0

我嘗試獲取文本使用此代碼獲取此文本,但仍然失敗。 你可以分析什麼是錯的?在pos31898js - 使用previouselementsibling獲取文本

<table class="table table-bordered" border="1"> 
<tbody> 
<tr> 
<td rowspan="2"><div id="foto"><img src="http://a0.twimg.com/profile_images/378800000163861066/61dee118c22e6ddb6fea2ffdb2957bd7_normal.jpeg"></div></td> 
<td><div id="tweet31898">**GET THIS TEXT**</div>  
</td> 
</tr> 
<tr> 
<td> 
<input type="radio" name="pos31898" value="POS" onclick="addPOS(this.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-success">Pos</span> 
<input type="radio" name="pos31898" value="NON" onclick="addNON(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-warning">Non</span> 
<input type="radio" name="pos31898" value="NEG" onclick="addNEG(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-important">Neg</span> 
</td> 
</tr> 
</tbody> 
</table> 

回答

0

尋找例如,它沒有previousElementSibling,它在它的容器中的第一個元素。這是比較明顯的,如果你縮進HTML:

<table class="table table-bordered" border="1"> 
    <tbody> 
    <tr> 
     <td rowspan="2"> 
     <div id="foto"><img src="http://a0.twimg.com/profile_images/378800000163861066/61dee118c22e6ddb6fea2ffdb2957bd7_normal.jpeg"></div> 
     </td> 
     <td> 
     <div id="tweet31898">**GET THIS TEXT**</div> 
     </td> 
    </tr> 
    <tr> 
     <td> 
     <input type="radio" name="pos31898" value="POS" onclick="addPOS(this.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-success">Pos</span> 
     <input type="radio" name="pos31898" value="NON" onclick="addNON(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-warning">Non</span> 
     <input type="radio" name="pos31898" value="NEG" onclick="addNEG(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.innerHTML+' ');"><span class="label label-important">Neg</span> 
     </td> 
    </tr> 
    </tbody> 
</table> 

最簡單的辦法,當然是document.getElementById("tweet31898"),因爲有一個在divid。由於您的單選按鈕在name中有該號碼,因此您可以使用this.name.replace('pos', 'tweet')推導出id。例如:

onclick="addPOS(document.getElementById(this.name.replace('pos', 'tweet')).innerHTML + ' ')" 

Live Example | Live Source

但結構上做它,你想parentNode去的td,然後再次去了tr,然後previousElementSibling拿到以前tr,然後lastElementChild下井的td,然後firstElementChild才能到div

onclick="addPOS(this.parentNode.parentNode.previousElementSibling.lastElementChild.firstElementChild.innerHTML + ' ')" 

Live Example | Live Source

+0

感謝您的迴應。我知道如果使用id獲得elemetn,但我有像我的帖子上面的情況,可悲的是我不能使用getelementbyid – user2597016

+0

@ user2597016:你可以用你發佈的內容,注意這個例子。但正如你在評論我正在撰寫如何在結構上做到這一點。 –

+0

好的。我會先試一試 – user2597016