$(this).attr("id").slice(-1)正在工作,但$(this).id.slice(-1)无法正常工作

Kal*_*nka 1 javascript jquery laravel-5.3

我在刀片上添加了一个按钮作为变量,该按钮的属性如下所示

 var $btnDelete = $('<input />',{

                'id': 'btn_delete'+ x,
                'type':'button',
                'name':'btn_delete'+ x,
                'class':'btn btn-danger editor_remove  editor_remove_leave_types ',          
                'onclick':'RemoveUpdateLeaveTypes(this)',
                'data-id':x  });
Run Code Online (Sandbox Code Playgroud)

注意:x只是一个变量(0,1,2等)

这是按钮附加到id ="xx2"div的方式: -

 $('#xx2').append($btnDelete);
Run Code Online (Sandbox Code Playgroud)

这里是上面提到的那个按钮的JavaScript函数:

function RemoveUpdateLeaveTypes(el)
Run Code Online (Sandbox Code Playgroud)

{

    var currentId=$(el).id.slice(-1);
    console.log('currentId '+currentId); 
Run Code Online (Sandbox Code Playgroud)

}

单击此按钮后,控制台上将显示此错误消息

Uncaught TypeError: Cannot read property 'slice' of undefined
at RemoveUpdateLeaveTypes (leavePolicyDetails.js:944)
at HTMLInputElement.onclick (leave-policies:1)
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用此命令,我将没有错误

var currentId=$(el).attr("id").slice(-1);
Run Code Online (Sandbox Code Playgroud)

请在此解释我的冲突,提前谢谢..

Pra*_*lan 5

idjQuery对象没有属性($(el)是一个jQuery对象).要获取DOM元素属性,请使用jQuery prop()(或attr())方法或通过索引获取DOM对象并获取属性.

var currentId = $(el).prop('id').slice(-1);
// or
var currentId = $(el)[0].id.slice(-1);
// or you can get DOM object using get() method
var currentId = $(el).get(0).id.slice(-1);
Run Code Online (Sandbox Code Playgroud)

更新:由于您将DOM对象作为参数传递,您可以直接从它获取id属性,因此不需要使用jQuery包装它.

// el === $(el)[0]
var currentId = el.id.slice(-1); 
Run Code Online (Sandbox Code Playgroud)