1
    <script type="text/javascript">
            $(document).ready(function(){
                    $('#number').change(function(){
                     $("#number option:selected").text();
                   //alert('Value change to ' + $(this).attr('value'));
                   $('#numberdiv').html('You selected: ' + $(this).attr('value'));
            });
        });
    </script>

<select id="number" data-corners="false" data-icon="false">
                    <option value="9 ">9 </option>
                    <option value="18 ">18 </option>
                    <option value="27 ">27 </option>
                    <option value="36 ">36 </option>
                    <option value="54 ">54 </option>
                </select>
                <div id="numberdiv"></div>

这工作正常,但我不能做的是显示当前值为 9 它可以在您更改为其他值后显示 9 的值,并且它们变回 9 我想要的是当我加载“您选择:9 “即使我没有在选择中进行更改也会显示

4

3 回答 3

3

You need to manually trigger the change event after the handler is registered using .trigge('change') or the shortcut .change()

$(document).ready(function () {
    $('#number').change(function () {
        $('#numberdiv').html('You selected: ' + this.value);
    }).change();
});

Demo: Fiddle

于 2013-10-23T03:00:45.277 回答
0

Try pulling the change function out and running it once on startup, like so:

$(document).ready(function () {
    var numberChange = function () {
        $("#number option:selected").text();
        //alert('Value change to ' + $(this).attr('value'));
        $('#numberdiv').html('You selected: ' + $(this).attr('value'));
    });

    $('#number').change(numberChange);
    numberChange();
});
于 2013-10-23T02:59:36.060 回答
0

Because the function you created inside the document.ready is capturing only the selected change function.

try adding

$('#numberdiv').html('You selected: ' + $(this).attr('value'));

outside of

 $('#number').change(function(){
                 $("#number option:selected").text();
               //alert('Value change to ' + $(this).attr('value'));
               $('#numberdiv').html('You selected: ' + $(this).attr('value'));
        });
于 2013-10-23T03:01:01.340 回答