简体   繁体   English

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

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

<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>

This will work for one selector but how do I make another script that changes a separate select. 这将适用于一个选择器,但如何使另一个脚本更改单独的选择。

You can use the ID of your selects, (btw, id A and B are a bit.. short..) 您可以使用选择的ID(顺便说一句,ID A和B有点.. short ..)

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

Or check what ID the select has: 或检查选择的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
    }
});

If the headers have id's that correspond to the select's id, you can use the select's id to obtain the corresponding headers. 如果标题具有与选择的ID对应的ID,则可以使用选择的ID获得相应的标题。 eg with header ids 'hA' and 'hB': 例如,标头ID为“ hA”和“ hB”:

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

Fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM