繁体   English   中英

如何将ID添加到所选的选择>选项元素

[英]How to add an ID to a select > option element that is selected

如何在选择>选项中添加ID:选择的HTML元素?

到目前为止,这是我的代码。

<!-- select time zone -->
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h3 id="stepOne"><b>Step 1:</b> Select your Time Zone</h3>
            <select class="form-control" name="timeZone" id="getTimeZone" onchange="getTimeZone()">
                <?php foreach ($time_zones as $key => $array) : ?>
                    <?php foreach ($array as $offset => $zone) : ?>
                        <option value="<?php echo $offset; ?>"><?php echo $zone; ?></option>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    <!-- end select timezone -->

    <!-- get timezone from dropdown -->
    <script>
        function getTimeZone() {
            // if option is selected add an ID attribute
            // then get that id attributes inner html
            var id = $("#getTimeZone").children("option:selected").attr("timeZoneSelected");
            var timeZone = document.getElementById("getTimeZone").value;
            document.getElementById("showTimeZone").innerHTML = timeZone;
            document.getElementById("timeZoneField").value = timeZone;
            document.getElementById("stepOne").className = "text-success";
        }
    </script>
    <!-- end get timezone from dropdown -->

所以基本上我循环遍历时区列表。 当用户选择时区时,我想为该选项添加ID,例如id="timeZoneSelected"

然后我想抓住那个特定选项元素的innerHTML。

正如您所看到的,我的代码无效,具体如下:

var id = $("#getTimeZone").children("option:selected").attr("timeZoneSelected");

我哪里错了?

要执行您需要的操作,您只需在change事件处理程序中检索所选选项的value和内部文本即可。 无需动态更新标识符或类属性。 尝试这个:

 $('#getTimeZone').change(function() { var name = $(this).find('option:selected').text(); var offset = this.value; $('#name').html(name); $('#offset').html(offset); $('#stepOne').addClass('text-success'); }); 
 .text-success { color: #0c0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h3 id="stepOne"><b>Step 1:</b> Select your Time Zone</h3> <select class="form-control" name="timeZone" id="getTimeZone"> <option value="-6">CST</option> <option value="0">GMT</option> <option value="+8">SGT</option> </select> </div> </div> <div id="name"></div> <div id="offset"></div> 

请注意,我修改了您的代码以使用不显眼的事件处理程序,因为on*事件属性被认为是过时的。

暂无
暂无

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

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