将id值从css类提取到javascript变量

时间:2018-01-19 08:47:57

标签: javascript jquery css

我有一个ul菜单,我想从中检索某些信息:

<ul id="form_builder_sortable" class="sortable rightDiv session1">
    <li class="draggable ui-state-highlight item id10" name="Maths">Maths<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
</ul>

我在javascript中有一个函数:

function getSessionDatas()
{
    var sessions = [];
    $('.rightDiv').each(function(index)
    {
        var session = $.trim($(this).text().slice(0, -1)).split("×");
        var sessionData = [];
        for (var i = 0; i < session.length; i++)
        {
            var s = {
                subjectOrder: i,
                subjectID: subs[session[i]]
            };
            sessionData.push(s);
        }
        var ses = {
            sessionNo: index,
            sessionData: sessionData
        };
        sessions.push(ses);
    });
}

下面:

var s = {subjectOrder:i, subjectID:<get id here>};

我想根据<li>项的类来分配主题ID,在这种情况下,在类中有id10。在这种情况下,如何将subjectID指定为10?

3 个答案:

答案 0 :(得分:7)

我建议你使用data-*前缀自定义属性,可以使用.data(key)方法检索。

$('.rightDiv li').each(function(index) {
  var id = $(this).data('id')
  console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="form_builder_sortable" class="sortable rightDiv session1" >
  <li data-id="10" class="draggable ui-state-highlight item" name="Maths">Maths<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
  <li data-id="11" class="draggable ui-state-highlight item" name="Maths">English<button onclick="deleteElement(event)" class="delbtn">&times</button></li>
</ul>

对于那些不使用jQuery的人,可以使用HTMLElement.dataset属性

获取相同内容
var id = this.dataset.id;

答案 1 :(得分:2)

虽然这不是一个特别好的方法,但只要您可以预测特定模式,就可以从元素的类中检索特定的类名。在这种情况下,例如,所需的类名称以id

的字符串开头
// elem:   a single node reference, the element from which
//         you want to retrieve a specific class-name;
// prefix: String, the string with which the required
//         class-name(s) begins.
function retrieveClassByPrefix(elem, prefix) {

  // either elem, or prefix, are undefined or otherwise
  // falsey we quit here:
  if (!elem || !prefix) {
    return false;
  }

  // otherwise we convert the classList of the element into
  // an Array, using Array.from() on the result returned from
  // elem.classList, and then use Array.prototype.filter()
  // to filter the Array:
  return allClasses = Array.from(elem.classList).filter(

    // currentClass - using an Arrow function - is a reference
    // to the current class-name of the Array of class-names over
    // which we're iterating; if the currentClass String begins
    // with the supplied String ('prefix') then that class-name
    // is retained in the Array:
    currentClass => currentClass.startsWith(prefix)
  );

}

let idClassName = retrieveClassByPrefix(
  document.querySelector('#form_builder_sortable > li:first-child'), 'id'
);

答案 2 :(得分:0)

您可以获取li元素的类,并找到与idXX匹配的

var regexId = /id([0-9]+)/gi
$('.rightDiv').each(function( index ) {
 //do some stuff
  $(this).find("li").each(function(){
      var classes = $(this).classes.split(/\s+/); // get the classes in an array
      for(var c in classes){
        c = classes[c]; //one classe
        var regexExec = regexId.exec(c);
        if(regexExec  && regexExec.length > 1){
                var id = regexExec[1];
               //do your stuff with the id 
               break;
           }
      }
   }
}