使用jquery从循环div中获取隐藏值

时间:2012-11-03 13:02:04

标签: jquery loops

我有一个搜索按钮。单击搜索按钮时,它将生成以下代码:

<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?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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()会更快,因为你的输入只有div的一个dom级别而.children()只搜索一个级别虽然.find()穿过整棵树来寻找所有可能的候选人。

答案 2 :(得分:1)

在点击处理程序中使用event参数,如下所示:http://jsfiddle.net/wE6JK/