如何从所选元素中获取数据?

时间:2016-10-26 05:04:02

标签: javascript jquery jquery-ui-selectable

页面包含html

<ol id="selectable">
    <li class="ui-widget-content word">I've</li>
    <li class="ui-widget-content word">got</li>
    <li class="ui-widget-content word">a</li>
    <li class="ui-widget-content word">job</li>
</ol>

我尝试从li元素中获取数据

$(function() {
    $("#selectable").selectable({
        stop : function() {
            var result = $("#select-result");
            $(".ui-selected", this).each(function() {   
                //getting data from an element
                var value = $("#selectable li").data(this);
                console.log("value"+value); //this outputs to `value[object Object]`    
            });
        }
    });

});

如何从所选元素中获取数据?

4 个答案:

答案 0 :(得分:0)

我想你需要li元素中的文本

$('.ui-widget-content').click(function(){
     console.log($(this).text());
});

我会这样做

cherry-pick

答案 1 :(得分:0)

你可以这样做:

function getDATA(){    
    var data;
    $("#selectable li").each(function() {
         data += $(this).text();
    })

    console.log(data);
}

答案 2 :(得分:0)

您可以使用所选属性

&#13;
&#13;
$( "#selectable" ).selectable({
    selected: function( e, ui ) {
        if ($( ui.selected ).hasClass( "ui-state-highlight" )) {
            $( ui.selected ).removeClass( "ui-state-highlight" );
        } else {
            $( ui.selected ).addClass( "ui-state-highlight" );
        }
        console.log(ui.selected.innerHTML);
    },    
    unselected: function( e, ui ) {
        $( ui.unselected ).removeClass( "ui-state-highlight" );    
    }
});
&#13;
ul {margin: 0; padding: 0; list-style-type: none; width: 50%;}
ul li {padding: 0.4em; margin: 0.2em; cursor: pointer; font-size: 0.8em;}
&#13;
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<ol id="selectable">
    <li class="ui-widget-content word">I've</li>
    <li class="ui-widget-content word">got</li>
    <li class="ui-widget-content word">a</li>
    <li class="ui-widget-content word">job</li>
</ol>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

  

为什么不使用

var foo = $('#selectable').find(':selected').data('id');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<ol id="selectable">
    <li data-id="I've" class="ui-widget-content word">I've</li>
    <li data-id="got" class="ui-widget-content word">got</li>
    <li data-id="a" class="ui-widget-content word">a</li>
    <li data-id="job" class="ui-widget-content word">job</li>
</ol>