2012-03-04 170 views
1

我有HTML:獲取嵌套元素值

<div> 
    <label> 
     <input type='radio' name='a'> 
     <span></span> 
     <input type='hidden' value='1'> 
    </label> 
    <label>... 
</div> 

我需要通過點擊事件標籤上得到隱藏的輸入值。

我的JavaScript是這樣的:

$('label').live('click', function() { 

     var value = $(this).children('input:hidden').val(); 

    }); 

但是,這是不行的。任何人都可以幫忙嗎?

+0

那麼,你有'價值'變量那裏,但你似乎沒有做任何事情。 – BoltClock 2012-03-04 08:41:08

+0

在Chrome瀏覽器中試用console.log($(this).children('input:hidden').val())來查看控制檯選項卡 – dotoree 2012-03-04 08:44:24

+0

「BoltClock」中的值,這與我將如何處理此值無關。這不是一個問題。我的問題是獲得這個價值 – 2012-03-04 08:51:43

回答

1

正常工作:

<div> 
    <label> 
     <input type='radio' name='a'> 
     <span></span> 
     <input type='hidden' value='1'> 
    </label> 
</div> 
<script type="text/javascript"> 
    $('label').live('click', function() { 
     var value = $(this).children('input:hidden').val(); 
     console.log(value); 
    }); 
</script> 

輸出:1

1
<form action="form_action.asp" method="get"> 
Email: <input type="text" name="email" /><br /> 
<input type="hidden" name="country" value="Norway" /> 
<input type="submit" value="Submit" /> 
    </form> 


$(function() { 
$('label').on('click', function() { 
    var value = $(this).children('input:hidden').val(); 

}); 

});

1

首先,除非你絕對要,你應該避免live()的功能。根據jQuery的版本,使用bind()click()on()

但你的代碼工作正常,看this Fiddle