Javascript追加并添加所选项

时间:2014-01-20 07:41:03

标签: javascript php jquery select

我正在尝试将selected添加到已在对象中呈现的选项值,但是下面的选项不会添加到选项值,即使它们是相等的。忽略所选的添加,是因为在执行此操作后附加?

eventClick: function(calEvent, jsEvent, view) {
    var startFormat = $.fullCalendar.formatDate(calEvent.start, "dd / MM / yyyy");
    var form = $("<form id='changeName'>" +
        "<h3 class='eventHeader'>Edit Event: " +startFormat+ " </h3>" +
        "</div></form>");

    form.append("<div class='controls'>" +
        "<label class='control-label' for='title'>Language: </label>" +
        "<select class='span3' id='lang' name='lang'>" +
        <?php foreach($languages as $language): ?>
        "<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
        <?php endforeach; ?>
        "</select>" +
        "</div>");

    $("#lang option").each(function(){
        if ($(this).val() == calEvent.lang)
            $(this).attr("selected","selected");
    });
}

2 个答案:

答案 0 :(得分:0)

而不是:

$(this).attr("selected","selected");

尝试使用.prop()

$(this).prop("selected", true);

更新

您可以使用.done()方法并改为使用change事件:

form.append("<div class='controls'>" +
    "<label class='control-label' for='title'>Language: </label>" +
    "<select class='span3' id='lang' name='lang'>" +
    <?php foreach($languages as $language): ?>
    "<option value='<?=$language->id;?>'><?=$language->title;?></option>" +
    <?php endforeach; ?>
    "</select>" +
    "</div>").done(function(){
          $(document).on('change', "#lang", function(){
               $('option', this).each(function(){
                  if ($(this).val() == calEvent.lang)
                    $(this).prop("selected", true);
               });
          }).change();  //<------fire the change event here when appended in dom
    });

答案 1 :(得分:0)

这只是一个例子:

<?php
$array = array('lang1' => 'option1', 'lang2' => 'option2');
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="jquery.js" type="text/javascript"></script>
    </head>
    <body>
        <select id="a_select"></select>
        <script>
            $(function() {

                var select_keys = [<?php foreach ($array as $key => $value) {echo "'$key', ";} ?>];
                var select_values = [<?php foreach ($array as $value) {echo "'$value', ";} ?>];

                $(select_values).each(function(i, item) {
                    var option = $('<option>'+ item +'</option>');
                    option.attr('value', select_keys[i]);
                    $('#a_select').append(option);
                });
            });
        </script>
    </body>
</html>

更新:添加了键值。

您可以使用ajax从另一个脚本加载此值,这将更容易&amp;清洁剂。