简体   繁体   中英

Get all unique data attribute values by value string separated by comma to list

I have this dynamic HTML

<select id='posto'>
  <select>
    <ul id="nazioni">
      <li data-dal="Europa, Mediterraneo">Italia</li>
      <li data-dal="Europa, Mediterraneo">Spania</li>
      <li data-dal="Asia">Cina</li>
      <li data-dal="Europa, Asia, Mediterraneo">Turchia</li>
      <li data-dal="Africa, Mediterraneo">Egitto</li>
      <li data-dal="Europa">Francia</li>
      <li data-dal="Europa">Svezia</li>
    </ul>

and I'm trying to fill in the select with tags with the 'data-dal' values which I'm trying to split into separate values by the comma and space. I'm a fresh jQuery and Javascript novice, but I've managed to piece together some sort of code from what I found here on stackOverflow and in the jQuery manual but wasn't able to piece together all the pieces into my desired code.

var items = {};
$('#nazioni li').each(function () {
  items[$(this).data('dal').split(', ')] = true;
});

var result = new Array();
for (var i in items) {
  result.push('<option>' + i + '</option>');
}

$('#posto').show().empty().append(result.join());

$('#posto').change(function () {
  var selected = $(this).find('option:selected').text();
  $('li[data-dal=' + selected + ']').show();
  $('li[data-dal!=' + selected + ']').hide();
});

http://jsfiddle.net/urnPG/ I jsfiddled it. I'm unable to split the data-dal values into separate values. I'd appreciate any help or pointers in better ways to do this.

I am not sure if I have understood your question right. But let me help you with what I can. First of all heres the JSFIDDLE Updated.

I could split the <li> elements values into a unique values array and populate the <Select> with these values.

$('#nazioni li').each(function () {
   var arr = $(this).data('dal').split(", ");
   items = items.concat(arr);
 });
 var sorted = unique(items);

This function gets the unique values of the list.

function unique(list) {
   var result = [];
   $.each(list, function(i, e) {
     if ($.inArray(e, result) == -1) result.push(e);
       });
   return result;
}

I then tried to show up all the <li> elements corresponding to the drop down value that is selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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