【问题标题】:jQuery Append UL with LI with value from dropdownlist on button clickjQuery Append UL with LI with value from dropdownlist on button click
【发布时间】:2009-07-13 11:06:52
【问题描述】:

我有一个下拉列表:

<select id="ContentList" name="ContentList">
  <option value="">Please Select</option>
  <option value="TEST_TOP">TEST TOP</option>
</select>

我有一个可排序的列表:

<ul id="sortable">
  <li class="ui-state-default">First</li>
  <li class="ui-state-default">Second</li>
  <li class="ui-state-default">Third</li>
</ul>

我有一个按钮:

<input type="button" value="Add Section" id="btnAdd" class="button"/>

还有以下脚本:

<script type="text/javascript">
        $(function() {


            $("#sortable").sortable({
                placeholder: 'ui-state-highlight'
            });
            $("#sortable").disableSelection();

            $('#btnAdd').click(function() {

            });

        });

    </script>

当用户在下拉列表中选择某些内容并单击添加时,我希望将其作为具有类属性等的&lt;li&gt; 发送到可排序列表,下拉列表现在显示“请选择”选项。

不确定最好的方法。谢谢

【问题讨论】:

    标签: javascript jquery jquery-ui


    【解决方案1】:
    $("#sortable").append("<li class='ui-state-default'>"+
                              $("#ContentList option:selected").text()+"</li>");
    $("#ContentList option:selected").remove();
    

    应该做的伎俩...(:

    【讨论】:

    • 我选择了 if ($("#ContentList option:selected").val() != "") { $("#sortable").append("
    • " + $("#ContentList option:selected").val() + "
    • "); $("#ContentList option:selected").remove(); $('#ContentList').attr('selectedIndex', 0); }
  • 不要在js中嵌入html,如果你改变了标记,那么你需要两个改变!不好
  • 检查值似乎是个好主意(:您可能还想检查默认值是否未被选中,因此没有人将“请选择”添加到您的列表中......
  • 【解决方案2】:

    工作演示here

    $('#btnAdd').click(function() { 
    
       //cache sortable
       var $sortable = $("#sortable"); 
    
       //clone sortables first li, change the text to that of the 
       //chosen option and append it to the sortable this saves having 
       //html embedded within the js
    
       $sortable.children().eq(0)
                           .clone()
                           .text( $('#ContentList').val() )
                           .appendTo( $sortable ); 
    
       // cache select options
       var $items = $('#ContentList').children(); 
    
       //remove selected item
       $items.filter(':selected').remove() 
    
       //set first option to be selected
       $list.eq(0).attr('selected', true); 
    }); 
    

    【讨论】:

    • 哇!带有自定义演示的答案。谢谢!然而你的代码看起来很复杂,虽然它可能只是我。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签