2

<span>当用户更改 中的选项时,我正在尝试更新下面的 id 属性<select>,但真的很挣扎。

<h5 class="wide">
    Image to show:
    <span id="image-preview-6385" class="colorbox-preview">preview</span>
</h5>
<select id="agri-image-id" class="wide image-select" name="middle_header_service[agriculture][image_id]">
    <option value="-1">No image for this service</option>
    <option value="6176">Brick houses (150x80)</option>
    <option value="6175">Brick houses (little ... (150x53)</option>
</select>

到目前为止我的代码 -

jQuery('.image-select').change(function(e){

    selected_id = jQuery(this).val();
    jQuery(this).prev('h5 span.colorbox-preview').attr('id', 'image-preview-'+selected_id);

});

使用时我可以得到响应alert(jQuery(this).prev('h5')).attr('id')),但除此之外的任何内容都会返回为undefined. 有人可以告诉我我做错了什么吗?谢谢。

4

4 回答 4

3

以下任何一项都应该有效:

jQuery(this) // select box itself
         .prev('h5.wide') // prev h5 with class wide
         .find('span.colorbox-preview')  // search for span within h5
         .attr('id', 'image-preview-'+selected_id); // change id

或者

jQuery('h5.wide') // h5 itself
    .find('span.colorbox-preview').attr('id', 'image-preview-'+selected_id);
于 2012-06-28T15:52:10.793 回答
1

试试这个

现场演示

jQuery('.image-select').change(function(e) {    
    selected_id = jQuery(this).val();
    jQuery(this).siblings('h5').children('span.colorbox-preview').attr('id', 'image-preview-' + selected_id);
});​
于 2012-06-28T15:55:30.257 回答
1

当你穿越时,你一次只能去一个方向。您正在尝试使用和在同一个选择器中转到兄弟姐妹prev(),查看不起作用的兄弟姐妹。

 /* traverse to sibling*/ 
jQuery(this).prev('h5')     
/* sibling H5 is now current object, look within it*/
.find('span.colorbox-preview')
/* span now current object, do something with it*/
.attr('id', 'image-preview-'+selected_id);
于 2012-06-28T15:58:47.893 回答
1

恕我直言,一个元素的 id 不应该改变,因为它使 JS 引用这个元素变得很棘手。

我假设您正在使用链接到<span>id 的 CSS 背景图像,但您可以使用<img>元素并更改其 src 属性,并在 selected_id 为 -1 时隐藏图像

HTML:

<h5 class="wide">
    Image to show:
    <img id="image-preview" class="colorbox-preview" src="blank.gif">
</h5>
<select id="agri-image-id" class="wide image-select" name="middle_header_service[agriculture][image_id]">
    <option value="-1">No image for this service</option>
    <option value="6176">Brick houses (150x80)</option>
    <option value="6175">Brick houses (little ... (150x53)</option>
</select>

Javascript:

jQuery('.image-select').change(function(e){
    selected_id = jQuery(this).val();
    image = jQuery("#image-preview");

    if (selected_id == -1) {
        image.attr("src", "blank.gif");
    else {
        image.attr("src", "preview_" + selected_id + ".gif");
    }
});
于 2012-06-28T16:03:05.210 回答