我有一个包含许多 div 的页面,如下所示,它是一个色样页面,即拇指大小的图像。我要做的是:当用户将鼠标悬停在图像样本上时,它必须显示名称为“描述性名称”的输入字段的值。 我遇到的困难是访问该输入字段的值。图像嵌套在标签中。标签和输入字段是兄弟。,
我的伪代码是这样的:
$('label.color-options img').each(function(){
$(this).mouseover(function(){
var descriptiveName = $(this).upOneLevel().sibling().('input.swatch- desciptive-name').value);
$('#display-descriptive-name').html(descriptiveName);
}) })
页面标记是这样的:
<div id="display-name"> </div>
<!-- END MAIN PRODUCT IMAGE -->
<!-- the page is full of these color swatches -->
<div class="color-swatch-wrapper">
<input type="hidden" value="Avacado 77" name="descriptive-name" class="swatch-descriptive-name" />
<input type="radio" name="id[10]" value="129" id="attrib-10-129" class="color-swatch-radio-btn" />
<label class="attribsRadioButton color-options" for="attrib-10-129">
PP77<br />
<img src="images/attributes/artichoke_green.jpg" alt="" width="260" height="320" />
</label>
</div>
提前致谢
最佳答案
首先,您不需要在循环中附加事件处理程序,要获取 input
元素的值,您可以使用 val()
。
你可以像这样使用parent().siblings()
:
$('label.color-options img').mouseover(function(){
var descriptiveName = $(this).parent().siblings('input.swatch-desciptive-name').val();
$('#display-descriptive-name').html(descriptiveName);
});
或者,您可以使用 closest()
和 find()
:
$('label.color-options img').mouseover(function(){
var descriptiveName = $(this).closest('.color-swatch-wrapper').find('input.swatch-desciptive-name').val();
$('#display-descriptive-name').html(descriptiveName);
});
我会推荐后者,因为如果您更改这些元素的 HTML 结构,只要保留类名,它就不会中断。
关于javascript - 我如何使用 jQuery 访问一个级别上的输入值,然后是其兄弟级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23836260/