2014-11-21 120 views
-3

的index.html的document.getElementById返回NULL

<body> 

    <script src="js/event_handler.js"></script> 

    <div id="some_wrapper"></div> 

</body> 

event_handler.js

$(document).ready(function() { 
    ... 

    $('#some_wrapper').append (someHTMLcode); 

    foo(someTagIdIntoTheNewHtmlCode); 
} 

//Search if the tag id exist 
function foo(tag_id){ 
    if(document.getElementById(tag_id) == null){ 
     console.log('#' + tag_id + " not found"); 
     return; 
    } 
    console.log('#' + tag_id + " found"); 
} 

當我追加到#some_wrapper的HTML代碼,一切都顯示成功,但如果我要處理的代碼,例如。 document.getElementById(tag)返回總是爲空。 爲什麼?

+5

當你使用'document.getElementById'時'''''''document.getElementById(tag)'... S ee:https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById – 2014-11-21 15:25:31

+1

在相關說明中,如果您使用的是jQuery,那麼爲什麼要執行'document.getElementById'? – j08691 2014-11-21 15:26:31

+0

在相關(更有幫助)的筆記上,您可以使用內置的JQuery方法遍歷DOM [''''''''''](http://api.jquery.com/find/)。 – theWanderer4865 2014-11-21 15:28:02

回答

-2

這項工作fiddel

function foo(tag){ 
    if($('#' + tag).length){ 
     alert('#' + tag + " found"); 
     return; 
    } 
    alert('#' + tag + " not found"); 
} 

試試這個

+0

,他說「發現」但標記不存在 – user3115251 2014-11-21 15:37:04

+0

反應是0 – ashkufaraz 2014-11-21 15:40:35

+0

console.log($('#'+ tag_id).length);嘗試使用 – user3115251 2014-11-21 15:44:26

1

的document.getElementById需要元素的id是我們不需要以 '#'

前綴試試這個:

document.getElementById(tag) 
+0

試過了,但還是沒找到 – user3115251 2014-11-21 15:36:29

相關問題