无法从列表项中获取id

时间:2022-01-21 06:52:32

I'm trying to pull out the value from the id attribute from a list item but the javascript runtime is throwing an error saying attr is not supported. What am I missing here?

我试图从列表项中的id属性中提取值,但javascript运行时抛出一个错误,说不支持attr。我在这里想念的是什么?

Getting the first list item in the list then trying to get the id from it.

获取列表中的第一个列表项,然后尝试从中获取id。

$("#sortable").sortable({
    start: function(event, ui) {
        var firstindex = $("li.imagethumbs").get(0);
        //console.log(firstindex);
        var id = firstindex.attr('id'); //error is thrown here
        $(ui.item).data("startindex", ui.item.index());
        // $(ui.item).data("firstindexid", id);
    },
    stop: function(event, ui) {
        self.sendUpdatedIndex(ui.item);
    }
});

2 个解决方案

#1


3  

The problem is because get(0) returns a DOMElement, not a jQuery object, and DOMElements do not have the attr() method.

问题是因为get(0)返回DOMElement而不是jQuery对象,而DOMElements没有attr()方法。

Instead you can access the id property of the DOMElement:

相反,您可以访问DOMElement的id属性:

var item = $("li.imagethumbs").get(0);
var id = item.id;

Or to use jQuery, if you want to retrieve the first element in a set use first();

或者使用jQuery,如果要检索集合中的第一个元素,请使用first();

var $firstLi = $("li.imagethumbs").first();
var id = $firstLi.attr('id');

#2


-1  

Try this : wrap fistindex in jQuery because $("li.imagethumbs").get(0); will return javascript object and you need jQuery object to call attr() method

试试这个:在jQuery中包装fistindex因为$(“li.imagethumbs”)。get(0);将返回javascript对象,您需要jQuery对象来调用attr()方法

var id = $(firstindex).attr('id');

Or

    var $firstindex = $("li.imagethumbs:first");
    var id = $firstindex.attr('id');

#1


3  

The problem is because get(0) returns a DOMElement, not a jQuery object, and DOMElements do not have the attr() method.

问题是因为get(0)返回DOMElement而不是jQuery对象,而DOMElements没有attr()方法。

Instead you can access the id property of the DOMElement:

相反,您可以访问DOMElement的id属性:

var item = $("li.imagethumbs").get(0);
var id = item.id;

Or to use jQuery, if you want to retrieve the first element in a set use first();

或者使用jQuery,如果要检索集合中的第一个元素,请使用first();

var $firstLi = $("li.imagethumbs").first();
var id = $firstLi.attr('id');

#2


-1  

Try this : wrap fistindex in jQuery because $("li.imagethumbs").get(0); will return javascript object and you need jQuery object to call attr() method

试试这个:在jQuery中包装fistindex因为$(“li.imagethumbs”)。get(0);将返回javascript对象,您需要jQuery对象来调用attr()方法

var id = $(firstindex).attr('id');

Or

    var $firstindex = $("li.imagethumbs:first");
    var id = $firstindex.attr('id');