在类中查找下一个select元素

时间:2014-11-17 17:47:20

标签: jquery

我有类似以下HTML的内容:

<div class="someClass">
    <div>
        <span>first</span><select id="first"></select>
        <span>second</span><select id="second"></select>
    </div>
    <div>
        Some text...
    </div>
    <div>
        <span>third</span><select id="third"></select>
        <span>fourth</span><select id="fourth"></select>
    </div>
</div>

我想用jquery,在更改一个select元素时,查找(填充选项)下一个select元素。 像这样:

$(".someClass").on("change", "select", function(){
    $(this).closest(".someClass").find("select").next();
});

2 个答案:

答案 0 :(得分:2)

以下是一个例子,无论何时更改一个选项,都会在下一个选项中添加一个新选项。

$('select').change(function () {
    var idx = $('div.someClass select').index(this);
    $('div.someClass select').eq(idx + 1).append('<option>3</option>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="someClass">
    <div> <span>first</span>

        <select id="first">
            <option>1</option>
            <option>2</option>
        </select> <span>second</span>

        <select id="second">
            <option>1</option>
            <option>2</option>
        </select>
    </div>
    <div>Some text...</div>
    <div> <span>third</span>

        <select id="third">
            <option>1</option>
            <option>2</option>
        </select> <span>fourth</span>

        <select id="fourth">
            <option>1</option>
            <option>2</option>
        </select>
    </div>
</div>

答案 1 :(得分:0)

可以尝试这个,更简单:

 $("div select").on( "change",function() {
    var sel = $(this).val();
    $(this).parent().find("select").val(sel);
})