2012-08-06 70 views
4

我有一個HTML DIV(我使用Twitter的引導來隱藏秀div2)看起來像這樣:如何使用jQuery訪問隱藏的Dom元素?

HTML:

<div id="div1"> 
    <button id="mybtn">Button</button> 
    <div id="div2" class="modal hide fade span12" style="display: none;"> 
    <button id="anotherButton" data-char="">AnotherButton</button> 
    </div> 
</div> 

使用jQuery我嘗試改變data-char而價值點擊mybtn。但沒有成功,因爲div2被隱藏。 console.log($('#anotherButton'));返回一個空數組。

有沒有辦法通過jQuery或Javascript訪問隱藏的DOM?

* 編輯:* 通過嘗試這種不工作更好,回報undefined

$('#mybtn').live('click', function(e) 
{ 
    //or e.preventDefault(); 
    $('#anotherbutton').attr("data-char", "assigned"); 
    alert($('#anotherbutton').attr("data-char")); 
}); 
+3

確保您已經包裹DOM準備好處理程序中的代碼。 – 2012-08-06 16:01:13

+1

它沒有關係,如果它隱藏,它只是很重要,如果它在頁面上。如果'console.log($('#anotherButton'));'真的沒有返回任何內容,或者它不在頁面上,或者在選擇器中存在拼寫錯誤。 – lbstr 2012-08-06 16:01:42

+0

讓我們看看更多的代碼。如果元素不可見,但仍然是DOM的一部分,這應該可以正常工作。 – 2012-08-06 16:02:05

回答

1

看起來data方法將無法在其處於隱藏狀態的元素工作。您應該使用attr方法。

這應該做工精細

$(function(){ 
    $("#mybtn").click(function(e){ 
    e.preventDefault(); 
     $("#anotherButton").attr("data-char","new value"); 
    });  
}); 

工作樣本http://jsfiddle.net/kshyju/a7Cua/4/

+0

好答案! 'e.preventDefault'讓我選擇你的答案! Thx – trouble 2012-08-07 08:18:22

1

的事實,這是隱藏的變化罷了。問題可能是js代碼在HTML按鈕之前。可以將它放在後面,或將其放入像$(document).ready()這樣的偵聽器,以確保在嘗試訪問它時已處理它。

+0

試試吧!沒有成功! Thx – trouble 2012-08-06 16:51:06

3

您可以將它

Live demo

$(function(){ 
    $('#anotherButton').attr('char', "assigned"); 
    alert($('#anotherButton').attr('char')); 
});​ 
上的按鈕進行

點擊

Live Demo

$(function(){ 
    $('#anotherButton').attr('data-char', "assigned"); 
    alert($('#anotherButton').attr('data-char')); 
});​ 
+0

該屬性需要爲'數據字符',而不是'字符'。 – 2012-08-06 16:07:39

+0

謝謝車廠,更新。 – Adil 2012-08-06 16:13:38

+0

當我使用它!它的返回'undefined' :( – trouble 2012-08-06 16:13:39

0

嘗試$(button:hidden)

這通常對這樣的事情,

出處:http://api.jquery.com/hidden-selector/