2015-06-16 53 views

回答

3

您需要使用此函数将事件源传递给myfn,并且您需要next而不是find,因为find将在后代中查找,接下来将查找兄弟。

Live Demo

的Javascript

function myfn(obj){ 
    var id= jQuery(obj).next('input').val(); 
    alert(id); 
    } 

在HTML

<div> 
    <img src=".." onclick="myfn(this)" > 
    <input type="hidden" value="1" > 
</div> 

作为一个附加的注释

  • 关闭inputimg标记与/
  • 将属性值括在双引号中,例如, typevalue

你可以绑定事件使用jQuery点击,而不是你有问题的内联事件绑定。我建议你使用一个类来绑定事件,为此你需要将类分配给img。这将使处理器中的this和$(this)可用。

Live Demo

的Html

<img src=".." onclick="myfn(this)" class="my-class"> 

Javacript/jQuery的

$('.my-class').click(function() { 
    var id = jQuery(this).next('input').val(); 
    alert(id); 
}) 
+0

人!你是一个拯救生命的人!谢谢!你能告诉我为什么“这个”不起作用吗?! – user2780757

+0

因为您使用javascript内联事件绑定绑定事件。 – Adil

+0

感谢您的额外信息! – user2780757

1

另一种选择是:

HTML:

<div> 
    <img src="http://placehold.it/120x120&text=image1" id="myimg" /> 
    <input type="hidden" value="1" /> 
</div> 

JS:

$('#myimg').click(function myfn(){ 
    var id= jQuery(this).next('input').val(); 
    alert(id); 
}); 

Live Demo

$('#myimg').click(function myfn() { 
 
    var id = jQuery(this).next('input').val(); 
 
    alert(id); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <img src="http://placehold.it/120x120&text=image1" id="myimg" /> 
 
    <input type="hidden" value="1" /> 
 
</div>

1

因为你正在寻找的IMG一个input元素。 您需要在父div或下一个元素中查找该输入元素。

试试这个

function myfn(){ 
    var id= jQuery(this).closest('div').find('input').val(); 
    alert(id); 
    } 
相关问题