Javascript JS 或 Jquery 创建唯一的跨度 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14044178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:32:07  来源:igfitidea点击:

JS or Jquery create unique span ID

javascriptjqueryhtml

提问by atlMapper

I'm creating a li item with a span inside. I've built an onclick function in the span to grab the parent li's ID to pass into a JSON get request. I'm unsure of how to create a unique ID and read it in the JS function. Since this is built dynamically I didn't build a switch but I feel like i'm missing another option. The problem here is that I can't capture the Li ID. I've tried this and also tried based on class, but all seem to be failing.

我正在创建一个里面有一个跨度的 li 项目。我在 span 中构建了一个 onclick 函数来获取父 li 的 ID 以传递到 JSON get 请求。我不确定如何创建唯一 ID 并在 JS 函数中读取它。由于这是动态构建的,我没有构建开关,但我觉得我错过了另一个选择。这里的问题是我无法捕获Li ID。我试过这个,也试过基于类,但似乎都失败了。

Li object creation:

Li 对象创建:

$("#jdLists").append('<li class="bigger" id = "' + item.ID + '">'+ 
  item.GROUP_NAME + 
  '<span title="Remove from list" class=" Sp icon icon-color icon-plus" style="float: right; vertical-align: middle;" '+
  'onclick="spAdd()"></span>' + 
  '</li>');

on click function:

点击功能:

function spAdd() {
  $(this).closest("li").attr('id');
}

回答by elclanrs

Try like this:

像这样尝试:

// Should work for most cases
function uniqId() {
  return Math.round(new Date().getTime() + (Math.random() * 100));
}

// Create elements properly and attach click event
// before appending to DOM so it delegates the event
var $li = $('<li/>', {
  'class': 'bigger',
  id: uniqId()
});

var $span = $('<span/>', {
  'class': 'Sp icon icon-color icon-plus',
  title: 'Remove from list',
  text: 'I\'m a span',
  click: function() { 
    alert( $(this).parent().attr('id') );
  }
});

$('#jsLists').append( $li.append( $span ) );

It should alert the li's random id on click. Also instead of inline css, add another class for those styles; better, simpler, easier.

它应该在点击时提醒 li 的随机 id。也不是内联 css,而是为这些样式添加另一个类;更好,更简单,更容易。

Demo:http://jsbin.com/avevim/1/edit(ctrl+enter to refresh and get new id)

演示:http : //jsbin.com/avevim/1/edit(ctrl+enter刷新并获取新id)

回答by Ross Allen

Underscore provides a uniqueIdfunction for cases like this. Rather than being tricky with dates and random numbers, it just keeps a global counter and increments it each time the function is called:

Underscore 为这种uniqueId情况提供了一个函数。它不会处理日期和随机数,而是保留一个全局计数器并在每次调用函数时递增它:

var idCounter = 0;
_.uniqueId = function(prefix) {
  var id = '' + ++idCounter;
  return prefix ? prefix + id : id;
};