0

この背後にあるコードを作成しようとすると問題が発生します。選択オプションの選択に基づいて、合計 4 つのオプションで div を表示/非表示にしようとしています。

2つの選択要素があります

<select>
    <option value="value1">Value 1</option>
    <option value="value2">Value 2</option>
</select>

<select>
    <option value="value3">Value 3</option>
    <option value="value4">Value 4</option>
</select>

組み合わせは

値1-値3 値1-値4

値2-値3 値2-値4

2 番目の select 要素は、最初の select 要素から選択するまで空であり、2 番目の要素から選択できるようになり、その値の div が表示されます。

divはそうなるでしょう。

<div id="value-1-3">value1-value3</div>
<div id="value-1-4">value1-value4</div>

<div id="value-2-3">value2-value3</div>
<div id="value-2-4">value2-value4</div>

これを行うのを手伝ってもらえますか?

4

3 に答える 3

2

この例のために、いくつかの ID をあなたの に与えます。それぞれ と をselects使用sel1sel2ます。また、あなたvalueoptionを単なる数字に変更します。そうしないと、のトリミングvalueまたは正規表現が必要になります。

$("#sel1").change(function() {
    $("#sel2").prop("disabled", false); //enable the second select
    $("#sel2").change(); //trigger a change event on select2
});

$("#sel2").change(function() {
    //Gather your select values
    var sel1Value = $("#sel1").val();
    var sel2Value = this.value;

    //Concatenate a selector and show it!
    $("div").hide(); //hide previously shown divs
    $("#value-" + sel1Value + "-" + sel2Value).show();
});

フィドル: http://jsfiddle.net/b7Q8s/18/

于 2013-10-03T13:36:00.050 に答える
0

私自身の提案は次のとおりです。

/* a more precise selector would be useful, whether by specifying an ancestor or
   by adding an id to the select elements. Binding the change event-handler: */
$('select').change(function(){
    /* creating the id of the relevant element to show using map(),
       to the string 'value-' plus whatever the map(), and get(), methods return: */
    $('#value-' + $('select option:selected').map(function(){
        // removing all non-numeric characters, returning the numbers:
        return this.value.replace(/\D+/g,'');
    /* forming an array with get(),
       joining the array elements together with hyphens, with join(),
       showing the element whose id matches the created string
       selecting siblings, removing the select elements from that selection,
       and hiding them: */
    }).get().join('-')).show().siblings().not('select').hide();
/* triggering the change event so the above always only shows/hides
   the relevant elements on loading the DOM: */
}).change();

JS フィドルのデモ

これは、設計上、2 番目の select 要素の表示を切り替えません。正直なところ、必要性がわかりませselectoption。選択のイベントを開始するために選択される非選択オプション(既に選択されているものchangeを選択したい場合でも)。option

参考文献:

于 2013-10-03T13:45:20.207 に答える