2012-05-04 123 views
0

我试图抓住被点击的图像的id,然后提交它的形式(通过设置隐藏的imagenr输入的val)。但是我不知道如何拉ID。选择图像ID

$(document).ready(function() { 
      $(".test-img").click(function() { 

       var imagevar = // How to grab the clicked img id? 
       $("#imagenr").val(imagevar); // set the img id to the hidden input 
       $("form#test-form").submit(); // submit the form 

      }) 
     }) 




<form action="#" method="post" id="test-form"> 
<input type="hidden" name="imagenr" id="imagenr" value=""> 

<img class="test-img" id="1" src="images/image1.jpg" alt=""/> 
<img class="test-img" id="2" src="images/image2.jpg" alt=""/> 

</form> 

回答

3

只需使用this.id,没有必要把它包在jQuery的。

var imagevar = this.id; 

Example on jsfiddle

0
$(".test-img").click(function() { 
    var imagevar = $(this).attr('id'); 
    $("#imagenr").val(imagevar); // set the img id to the hidden input 
    $("form#test-form").submit(); // submit the form 
}) 
0
$(document).ready(function() { 
     $(".test-img").click(function() { 

      var imagevar = $(this).attr('id'); 
      $("#imagenr").val(imagevar); // set the img id to the hidden input 
      $("form#test-form").submit(); // submit the form 

     }) 
    }); 
0

你可以抓住任何直接属性的值,使用类似:

$(this).attr('id'); 

好运。