如何使用 jquery .change() 在 html 中进行多个选择

How to make multiple selects in html with jquery .change()

本文关键字:选择 html jquery 何使用 change      更新时间:2023-09-26
<center>
    <h3> A </h3>
    <h4> vs </h4>
    <h3> B </h3>
    <h4> 60 - 70 </h4>
</center>
<div class="12u$">
    <div class="select-wrapper">
        <select name="teamA" id="A" style="max-width:30%;">
            <option value="">- TeamA -</option>
            <option value="1">Kansas</option>
            <option value="1">Oklahoma</option>
            <option value="1">Texas</option>
            <option value="1">Notre Dame</option>
        </select>
    </div>
</div>
<div class="12u$">
    <div class="select-wrapper">
        <select name="teamB" id="B" style="max-width:30%;">
            <option value="">- TeamB -</option>
            <option value="1">Kansas</option>
            <option value="1">Oklahoma</option>
            <option value="1">Texas</option>
            <option value="1">Notre Dame</option>
        </select>
    </div>
</div>
<script>
    $("select")
        .change(function() {
            var str = "Team A";
            $("select option:selected").each(function() {
                str = $(this).text() + " ";
            });
            $("h3").text(str);
        })
        .change();
</script>

这将适用于一个选择器,但是我如何制作另一个更改单独选择的脚本。

你可以使用你选择的 ID,(顺便说一句,id A 和 B 有点短..)

$("#A").change();
$("#B").change();

或者检查所选内容的 ID:

$("select").change(function(){
    if(this.id == "A")
    {
        // Its the first one that changed
    }
    else if(this.id == "B")
    {
        // Its the second one that changed
    }
});

如果标头具有与选择的 id 对应的 id,则可以使用选择的 id 来获取相应的标头。 例如,标头 ID 为"hA"和"hB":

$( "select" ).change(function () {
    $('#h' + this.id).text(this.options[this.selectedIndex].text);
});

小提琴