0

ページで何度も使用される選択ボックスがあります。

<div class="some-div">
    <a class="maybe">Maybe</a>
    <select class="selectclass">
        <option>Maybe</option>
        <option>Yes</option>
        <option>No</option>
    </select>
</div>

jQuery を使用して、選択したオプションの数に応じて「a」要素にクラスを追加するにはどうすればよいですか? このサイトは多言語であるため、クラスは値からではなく、オプションの数から取得する必要があります。1 番目は「たぶん」、2 番目は「はい」、3 番目は「いいえ」です。選択はページで何度も使用されるため、実行中のものにのみ適用する必要があります。

前もって感謝します!

4

4 に答える 4

1

更新 - OPの要件に従って

このDEMOで何かをしようとしていますか?

jQuery:

$('.selectclass').change(function(){

    var number = $(this).val();
    var value = $("option^[value=" + number + "]").text();

    $(this).parent().find('a').html(value);    
    $(this).parent().find('a').attr('class', 'opt' + number);

});​

HTML:

<div class="some-div">
    <a class="opt1">Maybe</a>
    <select class="selectclass">
        <option value="1">Maybe</option>
        <option value="2">Yes</option>
        <option value="3">No</option>
    </select>
</div>​

CSS:

.opt1{ color:blue; }
.opt2{ color:green; }
.opt3{ color:red; }​
于 2012-08-06T10:55:06.770 に答える
1

まず最初に、オプションの「値」属性を使用するように HTML を変更します。これにより、多言語アーキテクチャを気にする必要がなくなります。

<div class="some-div">
<a class="maybe">Maybe</a>
<select class="selectclass">
    <option value="1">Maybe</option>
    <option value="2">Yes</option>
    <option value="3">No</option>
</select>

ddl change メソッドにバインドし、jquery を使用して ddl の値を見つけます。

$('.selectclass').bind("change", function() {  
var option = $(this).val();
if (option == 1)
{
//your code
}
else if...
});
于 2012-08-06T10:58:11.623 に答える
1

HTML

オプションにいくつかの値を追加します...

<div class="some-div">
    <a class="maybe">Maybe</a>
    <select class="selectclass">
        <option value="maybe">Maybe</option>
        <option value="yes">Yes</option>
        <option value="no">No</option>
    </select>
</div>​​​​​​

Javascript (jQuery)

競合を避けるために、実際のコードではセレクターをより具体的にする必要があります...

// add a `change` event to the select element
​$("select").on("change",function(){
    // get the value of the select element
    var val = $(this).val()
    // remove all classes from the `a` tag  and add the
    // recently got value as a class of the `a` tag
    $("a").removeClass().addClass(val)
})​​​​​​​​​

CSS

テストのためだけに...

</p>

.no{
    color: red;
}
.yes{
    color: green;
}

.maybe{
    color: orange;
}
​

デモ

事前に作成されたデモは、ここで見ることができます: http://jsfiddle.net/uBCJd/

于 2012-08-06T10:59:22.157 に答える
0

これにより、選択したオプションのインデックスが得られ、リンクのクラスとテキストが変更されます</p>

$(".selectclass").live("change",function(){
    var index = $(this).children("option:selected").index() + 1;
    $(this).parent().find('a').text(index+':'+$(this).val());
    $(this).parent().find('a').attr('class',index);
});​
于 2012-08-06T11:01:38.830 に答える