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

IMHO要素の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 に答える
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

これを試して

ライブデモ

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 に答える