我想在用户点击jquery中的img时获得最接近的输入值,我该怎么做?例如,如果用户单击img a,它将获得值"1"。
<img src="">a</img>
<input type="hidden" value="1" />
<img src="">b</img>
<input type="hidden" value="2" />
<img src="">c</img>
<input type="hidden" value="3" />
<img src="">d</img>
<input type="hidden" value="4" />
<img src="">e</img>
使用next()
$('img').click(function() {
var value = $(this).next().val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img src="" alt=a />
<input type="hidden" value="1" />
<img src="" alt=b />
<input type="hidden" value="2" />
<img src="" alt=c />
<input type="hidden" class=a value="3" />
<img src="" alt=d />
<input type="hidden" value="4" />
<img src="" alt=e />
更新:如果输入后有任何其他元素,则需要使用nextAll()
和first()
$('img').click(function() {
var value = $(this).nextAll('input').first().val();
// you can avoid first(), since val() return value of first element from selector
// var value = $(this).nextAll('input').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img src="" alt=a />
<input type="hidden" value="1" />
<span>hello</span>
<img src="" alt=b />
<input type="hidden" value="2" />
<span>hello</span>
<img src="" alt=c />
<input type="hidden" value="3" />
<span>hello</span>
<img src="" alt=d />
<input type="hidden" value="4" />
<img src="" alt=e />
尝试这个
$('img').click(function() {
var value = $(this).next().val();
});
$("img").click(function(){
alert($(this).parents('.input-group').find('input').val());
});
希望这对你有帮助!!
我想你的页面中会有其他img标记。在这种情况下,如果您可以用div包围这些img标记,并执行以下操作会更好。
<div id="parentDiv">
<img src="">a</img>
<input type="hidden" value="1" />
<img src="">b</img>
<input type="hidden" value="2" />
<img src="">c</img>
<input type="hidden" value="3" />
<img src="">d</img>
<input type="hidden" value="4" />
<img src="">e</img>
</div>
你应该输入的jquery是,
$("#parentDiv img").each(function(){
$(this).click(function(){
if($(this).next().val()){
alert($(this).next().val());
}
});
});
如果你的页面除了这些标签之外没有任何其他img标签,只需保持html的原样,并将这种代码的平静
$("img").click(function(){
if($(this).next().val()){
alert($(this).next().val());
}
});