[英]Define index of <li> element in <ul> list after jquery sortable
I hope you can help me with a little problem. 希望您能为我解决一点问题。 With my code I want to rename the element id's of my ul list, which are sorted by jquery sortable, but its not working properly. 用我的代码,我想重命名我的ul列表的元素ID,这些元素ID按可排序的jquery排序,但不能正常工作。 Sometimes it's working, but sometimes there's just an error: "Uncaught TypeError: Cannot read property 'id' of null" and it's renaming like: 1-2-3-4-5-6-6-8 .Maybe you can help me out. 有时它可以正常工作,但有时只是一个错误:“ Uncaught TypeError:无法读取null的属性'id'”,它的重命名为:1-2-3-4-5-6-6-8。也许您可以帮助我出来。
Here's my ul: 这是我的ul:
<ul class="example">
<li id="1" class="example"></li>
<li id="2" class="example"></li>
<li id="3" class="example"></li>
<li id="4" class="example"></li>
<li id="5" class="example"></li>
<li id="6" class="example"></li>
</ul>
js for jquery sortable: 用于可排序的js的js:
$('.example').sortable();
and here's my js for getting actual index and renaming li id: 这是我的js,用于获取实际索引并重命名li id:
function myFunction(){
var lenght = $(".example").length;
lenght = lenght -1;
for (var i=1; i<=lenght; i++){
var newIn = $('#'+i).index();
newIn = newIn +1;
var inold = document.getElementById(i).id;
if(newIn != inold){
var change = document.getElementById(i).id = newIn;
}
}
}
Thank you for giving me a hint! 谢谢你给我一个提示!
Thanks for your hint CBroe! 感谢您的提示CBroe! Its working like a charm now! 它的工作就像一个魅力!
function myFunction(){
$(".example").each(function(i) {
var row = $(this)
row.attr('id', '' + i);
});
}
this error occurred when you have a list of duplicate id's or not a continues id's like(3,2,4,1,6) here '5' is missing and you are just replacing id by accessing sequential number that is 'i' so when i will reach to 5 then "document.getElementById(i).id" this will give you '-1' because there is no li with id=5. 当您有重复ID的列表或没有连续ID的like(3,2,4,1,6)时出现此错误,这里'5'丢失了,而您只是通过访问序列号'i'来替换ID当我到达5时,“ document.getElementById(i).id”将给您“ -1”,因为没有li = 5的锂。 i hope this code will help you for your problem. 我希望这段代码对您的问题有所帮助。
function myfunction(){
$("li.example").each(function() {
var currentId = $(this).attr("id"); //id of each li
var newIn = $(this).index(); //index of each li starts from 0
newIn++;
if(currentId!==newIn)
{
$(this).attr("id",newIn);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.