2013-03-28 71 views
1

隱藏輸入元素的文本,我有以下的html代碼:如何從嵌套在一個div

<a class="tog" href="#">Click Me</a> 
<div class="result"> 
    <input type="hidden" name="hid" value="val01" /> 
    This is a container div 
</div> <br /> 
<a class="tog" href="#">Click Me</a> 
<div class="result"> 
    <input type="hidden" name="hid" value="val02" /> 
    This is a another container div 
</div> 

如何我可以從上<a>點擊隱藏輸入值?我正在嘗試使用此jQuery代碼,但它無法從那些隱藏的輸入元素中檢索值。

$(document).ready(function(){ 
$(".tog").click(function(){ 
    var $this=$(this); 
if (!$this.next(".result").data('loaded')){ 
    alert($this.next("input[name=hid]").val()); 
    } 
}); 
}); 
+0

嘗試'$ this.next()找到( 「輸入[名稱= HID]」)VAL( )'而不是 – 2013-03-28 07:57:38

回答

1

簡單

$(".tog").click(function() { 
    var $this = $(this); 
    if (!$this.next(".result").data('loaded')) { 
     alert($this.next(".result").children("input:hidden").val()); 
    } 
}); 
+1

據我所知,這是最簡單的,所以我標記了它,儘管所有答案都是有用的。如果有選擇接受多個答案,我也會標記其他人。 – stockBoi 2013-03-28 13:49:05

0

它應該是:

$(document).ready(function() { 
    $(".tog").click(function() { 
    var $this = $(this); 
    if (!$this.next(".result").data('loaded')) { 
     alert($this.next().find("input[name=hid]").val()); 
    } 
    }); 
}); 

Demo

0

與您的代碼的問題是,您使用的是next()它是由文檔是用來獲取緊隨其後在匹配元素集合中的每個元素的兄弟。如果提供了一個選擇器,只有當它與該選擇器匹配時纔會檢索下一個兄弟。。這裏你的'$ this'指向錨點,當你試圖執行$this.next("input[name=hid]").val()時,它沒有任何名爲「hid」的直接兄弟姐妹,這就是爲什麼你沒有定義。

試試這個代碼:

$(document).ready(function(){ 
    $(".tog").click(function(){ 
     var $this=$(this); 
    alert($this.next("div").find("input[name=hid]").val()); 
    }); 
}); 

jsfiddle

+0

非常快速的答覆謝謝你們大家。雖然解決方案非常簡單,但對我來說更難,因爲我是jquery的新手。我的問題現在解決了。再次感謝大家。 – stockBoi 2013-03-28 08:08:33

+0

@ user2132726所以請將其中一個標記爲答案。 http://stackoverflow.com/exout – arjuncc 2013-03-28 08:10:19

0

你可以做到以下幾點:

獲取下一個元素,它與結果類股利。從那裏你可以找到隱藏的輸入並獲得它的價值。

Demo

的Javascript:。

$(document).ready(function(){ 
    $(".tog").click(function(){ 
     var atag = $(this); 
     var hiddenInput = atag.next().find('input[type=hidden]'); 
     alert(hiddenInput.val());   
    }); 
});