2012-11-03 28 views
3

我有一個搜索按鈕。點擊搜索按鈕時,就會產生這樣的代碼:從jquery循環div中獲得隱藏值

<div class = 'clickedResult' title = 'click to see details'> 
<table>the result will br written in this table </table> 
<input type = 'hidden' class = 'form_id' value = '$form_id' /> 
<input type = 'hidden' class = 'status' value = '$status' /> 
</div> <br/> 

這段代碼中循環,循環去兩次循環的結果是這樣的

<div class = 'clickedResult' title = 'click to see details'> 
<table>the result will br written in this table </table> 
<input type = 'hidden' class = 'form_id' value = '14' /> 
<input type = 'hidden' class = 'status' value = 'latest' /> 
</div> 

<div class = 'clickedResult' title = 'click to see details'> 
<table>the result will br written in this table </table> 
<input type = 'hidden' class = 'form_id' value = '48' /> 
<input type = 'hidden' class = 'status' value = 'updated' /> 
</div> 

如果表中的一個被點擊,它會做這(使用jQuery)

$(".clickedResult").click(function() 
    { 
    $('.clickedResult input.form_id').each(function() 
     { 
    alert($(this).val()); 
    }); 
    }); 

它會提醒14和48 ...如何,如果我單擊第一個表中只有14警示?如果我點擊第二個表,它會提醒48?

回答

2
$(".clickedResult").click(function() { 
    alert($(this).find('input.form_id').val()); 
}); 
+0

非常感謝你..它的工作原理 –

2

使用$(this).children("input.form_id")而不是$('.clickedResult input.form_id')要經過僅是您點擊的div後代的form_id。

考慮您的示例,代碼應該是這樣的:

$(".clickedResult").click(function() { 
    console.log($(this).children("input.form_id").val()); 
}); 

另外一個可能會說,你的情況使用.children()代替.find()更快,因爲你的投入僅僅是一個DOM級別從下div和.children()只搜索一個深度,而.find()遍歷整棵樹以找到所有可能的候選人。

+1

非常感謝你..這一個也是工作 –