2014-02-26 28 views
-3

我試圖在它裏面的圖像上單擊作爲代碼時提醒div的id爲:如何使用javascript獲取html元素ID?

<html> 
<head> 
    <style type="text/css"> 
     .test1{ 
      width:500px; 
      background: #cc0000; 
      color:#fff; 
      height:200px; 
      margin:0px auto; 
     } 
    </style> 
    <script> 

     function hidediv(){ 
      var a = document.getElementById("divtobehide"); 
      alert(a); 
     } 
    </script> 
</head> 
<body> 

    <div id="divtobehide" class="test1"> 
     This is the div to be hiddenite 
     <img src="index.jpg" id="imgid" onclick="hidediv()" style="float:right;"> 
    </div> 
</body> 

這裏出現的警告框,但不顯示的ID。如何解決這個問題?

回答

6

當您使用document.getElementById()您已經知道id

你甚至可以這樣做:

function hidediv() 
{ 
    alert("divtobehide"); 
} 

它沒有多大意義,你所編寫的代碼的方式。也許有關於getElementById()如何工作的概念錯誤(誤解)?

如果你想操縱DOM對象,你已經可以做到這一點的ID:

function hidediv(nodeId) 
{ 
    var node; 

    node = document.getElementById(nodeId); 
    node.style.display = "none"; 
} 

在HTML指定相關的ID:

<img src="index.jpg" id="imgid" onclick="hidediv('divtohide')" style="float:right;"> 

這種方式可以重複使用功能和縱橫交錯的<img><div>節點。

0

我認爲你在尋找什麼更多的東西是這樣的:

<script> 
function hideParentElement(element){ 
    element.parentNode.style.display = 'none'; // Hide the parent. 
    alert(element.id); 
    alert(element.parentNode.id); 
} 
</script> 

<div id='forestImageContainer'>Outer div content<img id='clickable-image' alt='Click to hide' onclick='hideParentElement(this);'> more outer div content</div> 

這裏是jsfiddle of that

通常你會通過元素在onclick中通過處理程序(在這種情況下是onclick)作爲this執行操作。更好的辦法是將js onclick從主html中分離出來。

<script> 
$(function(){ 
    $('#clickable-image').click(function(){ 
     $(this).parent().hide(); 
     alert(this.id); 
     alert($(this).parent().attr('id')); 
    }); 
}) 
</script> 

<div id='forestImageContainer'>Outer div content<img id='clickable-image' alt='Click to hide'> more outer div content</div> 
+0

他需要警報箱爲什麼你這樣做? –

+0

只是覺得他只是在提醒這個ID作爲調試,因爲其他方面沒有什麼好處。 – Kzqai

0

試試這個:你可能會從使用jQuery,當時剛剛起步的,它可以簡化複雜的操作和瀏覽器的差異可能幫你寫一點點乾淨的代碼沒有任何 JavaScript的HTML中受益

alert(document.getElementById("imgid").parentNode()) 
0

OP要求獲得點擊元素的div ID,而不是如何隱藏元素。 獲取元素後,可以使用dot notation來訪問它的屬性。 這裏是你如何做到這一點:

var element = document.getElementById('id'); 
console.log(element.id); 

現在,如果你想要一個元素的父。這有點不同。將元素本身作爲函數的參數,通過在這些缺口之間添加「this」來實現。

<img src="index.jpg" id="imgid" onclick="hidediv(this)" /> 

更改函數標頭以允許傳遞參數。你可以給它命名,但是你想要的是我建議的「發件人」。

function hidediv(sender){} 

現在在函數裏面,可以通過使用點符號.parentNode得到發件人的父項。這將使你的功能工作,無論圖像被點擊或任何div的ID。警惕這隻會得到發件人的直接父母。

看看這個:http://jsfiddle.net/TASmS/

0

下面是簡單的解決方案。

function reply_click(clicked_id) 
{ 
    alert(clicked_id); 
} 
onClick="reply_click(this.id)" 
+0

嗨,你可以編輯你的答案,並使用降價將示例代碼移動到代碼塊。請正確縮進示例代碼。 –